Merge remote-tracking branches 'spi/topic/spidev', 'spi/topic/st-ssc4' and 'spi/topic...
[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                 /*
1490                  * POWER9 DD1 has an erratum where writing TBU40 causes
1491                  * the timebase to lose ticks.  So we don't let the
1492                  * timebase offset be changed on P9 DD1.  (It is
1493                  * initialized to zero.)
1494                  */
1495                 if (cpu_has_feature(CPU_FTR_POWER9_DD1))
1496                         break;
1497                 /* round up to multiple of 2^24 */
1498                 vcpu->arch.vcore->tb_offset =
1499                         ALIGN(set_reg_val(id, *val), 1UL << 24);
1500                 break;
1501         case KVM_REG_PPC_LPCR:
1502                 kvmppc_set_lpcr(vcpu, set_reg_val(id, *val), true);
1503                 break;
1504         case KVM_REG_PPC_LPCR_64:
1505                 kvmppc_set_lpcr(vcpu, set_reg_val(id, *val), false);
1506                 break;
1507         case KVM_REG_PPC_PPR:
1508                 vcpu->arch.ppr = set_reg_val(id, *val);
1509                 break;
1510 #ifdef CONFIG_PPC_TRANSACTIONAL_MEM
1511         case KVM_REG_PPC_TFHAR:
1512                 vcpu->arch.tfhar = set_reg_val(id, *val);
1513                 break;
1514         case KVM_REG_PPC_TFIAR:
1515                 vcpu->arch.tfiar = set_reg_val(id, *val);
1516                 break;
1517         case KVM_REG_PPC_TEXASR:
1518                 vcpu->arch.texasr = set_reg_val(id, *val);
1519                 break;
1520         case KVM_REG_PPC_TM_GPR0 ... KVM_REG_PPC_TM_GPR31:
1521                 i = id - KVM_REG_PPC_TM_GPR0;
1522                 vcpu->arch.gpr_tm[i] = set_reg_val(id, *val);
1523                 break;
1524         case KVM_REG_PPC_TM_VSR0 ... KVM_REG_PPC_TM_VSR63:
1525         {
1526                 int j;
1527                 i = id - KVM_REG_PPC_TM_VSR0;
1528                 if (i < 32)
1529                         for (j = 0; j < TS_FPRWIDTH; j++)
1530                                 vcpu->arch.fp_tm.fpr[i][j] = val->vsxval[j];
1531                 else
1532                         if (cpu_has_feature(CPU_FTR_ALTIVEC))
1533                                 vcpu->arch.vr_tm.vr[i-32] = val->vval;
1534                         else
1535                                 r = -ENXIO;
1536                 break;
1537         }
1538         case KVM_REG_PPC_TM_CR:
1539                 vcpu->arch.cr_tm = set_reg_val(id, *val);
1540                 break;
1541         case KVM_REG_PPC_TM_XER:
1542                 vcpu->arch.xer_tm = set_reg_val(id, *val);
1543                 break;
1544         case KVM_REG_PPC_TM_LR:
1545                 vcpu->arch.lr_tm = set_reg_val(id, *val);
1546                 break;
1547         case KVM_REG_PPC_TM_CTR:
1548                 vcpu->arch.ctr_tm = set_reg_val(id, *val);
1549                 break;
1550         case KVM_REG_PPC_TM_FPSCR:
1551                 vcpu->arch.fp_tm.fpscr = set_reg_val(id, *val);
1552                 break;
1553         case KVM_REG_PPC_TM_AMR:
1554                 vcpu->arch.amr_tm = set_reg_val(id, *val);
1555                 break;
1556         case KVM_REG_PPC_TM_PPR:
1557                 vcpu->arch.ppr_tm = set_reg_val(id, *val);
1558                 break;
1559         case KVM_REG_PPC_TM_VRSAVE:
1560                 vcpu->arch.vrsave_tm = set_reg_val(id, *val);
1561                 break;
1562         case KVM_REG_PPC_TM_VSCR:
1563                 if (cpu_has_feature(CPU_FTR_ALTIVEC))
1564                         vcpu->arch.vr.vscr.u[3] = set_reg_val(id, *val);
1565                 else
1566                         r = - ENXIO;
1567                 break;
1568         case KVM_REG_PPC_TM_DSCR:
1569                 vcpu->arch.dscr_tm = set_reg_val(id, *val);
1570                 break;
1571         case KVM_REG_PPC_TM_TAR:
1572                 vcpu->arch.tar_tm = set_reg_val(id, *val);
1573                 break;
1574 #endif
1575         case KVM_REG_PPC_ARCH_COMPAT:
1576                 r = kvmppc_set_arch_compat(vcpu, set_reg_val(id, *val));
1577                 break;
1578         default:
1579                 r = -EINVAL;
1580                 break;
1581         }
1582
1583         return r;
1584 }
1585
1586 /*
1587  * On POWER9, threads are independent and can be in different partitions.
1588  * Therefore we consider each thread to be a subcore.
1589  * There is a restriction that all threads have to be in the same
1590  * MMU mode (radix or HPT), unfortunately, but since we only support
1591  * HPT guests on a HPT host so far, that isn't an impediment yet.
1592  */
1593 static int threads_per_vcore(void)
1594 {
1595         if (cpu_has_feature(CPU_FTR_ARCH_300))
1596                 return 1;
1597         return threads_per_subcore;
1598 }
1599
1600 static struct kvmppc_vcore *kvmppc_vcore_create(struct kvm *kvm, int core)
1601 {
1602         struct kvmppc_vcore *vcore;
1603
1604         vcore = kzalloc(sizeof(struct kvmppc_vcore), GFP_KERNEL);
1605
1606         if (vcore == NULL)
1607                 return NULL;
1608
1609         spin_lock_init(&vcore->lock);
1610         spin_lock_init(&vcore->stoltb_lock);
1611         init_swait_queue_head(&vcore->wq);
1612         vcore->preempt_tb = TB_NIL;
1613         vcore->lpcr = kvm->arch.lpcr;
1614         vcore->first_vcpuid = core * threads_per_vcore();
1615         vcore->kvm = kvm;
1616         INIT_LIST_HEAD(&vcore->preempt_list);
1617
1618         return vcore;
1619 }
1620
1621 #ifdef CONFIG_KVM_BOOK3S_HV_EXIT_TIMING
1622 static struct debugfs_timings_element {
1623         const char *name;
1624         size_t offset;
1625 } timings[] = {
1626         {"rm_entry",    offsetof(struct kvm_vcpu, arch.rm_entry)},
1627         {"rm_intr",     offsetof(struct kvm_vcpu, arch.rm_intr)},
1628         {"rm_exit",     offsetof(struct kvm_vcpu, arch.rm_exit)},
1629         {"guest",       offsetof(struct kvm_vcpu, arch.guest_time)},
1630         {"cede",        offsetof(struct kvm_vcpu, arch.cede_time)},
1631 };
1632
1633 #define N_TIMINGS       (sizeof(timings) / sizeof(timings[0]))
1634
1635 struct debugfs_timings_state {
1636         struct kvm_vcpu *vcpu;
1637         unsigned int    buflen;
1638         char            buf[N_TIMINGS * 100];
1639 };
1640
1641 static int debugfs_timings_open(struct inode *inode, struct file *file)
1642 {
1643         struct kvm_vcpu *vcpu = inode->i_private;
1644         struct debugfs_timings_state *p;
1645
1646         p = kzalloc(sizeof(*p), GFP_KERNEL);
1647         if (!p)
1648                 return -ENOMEM;
1649
1650         kvm_get_kvm(vcpu->kvm);
1651         p->vcpu = vcpu;
1652         file->private_data = p;
1653
1654         return nonseekable_open(inode, file);
1655 }
1656
1657 static int debugfs_timings_release(struct inode *inode, struct file *file)
1658 {
1659         struct debugfs_timings_state *p = file->private_data;
1660
1661         kvm_put_kvm(p->vcpu->kvm);
1662         kfree(p);
1663         return 0;
1664 }
1665
1666 static ssize_t debugfs_timings_read(struct file *file, char __user *buf,
1667                                     size_t len, loff_t *ppos)
1668 {
1669         struct debugfs_timings_state *p = file->private_data;
1670         struct kvm_vcpu *vcpu = p->vcpu;
1671         char *s, *buf_end;
1672         struct kvmhv_tb_accumulator tb;
1673         u64 count;
1674         loff_t pos;
1675         ssize_t n;
1676         int i, loops;
1677         bool ok;
1678
1679         if (!p->buflen) {
1680                 s = p->buf;
1681                 buf_end = s + sizeof(p->buf);
1682                 for (i = 0; i < N_TIMINGS; ++i) {
1683                         struct kvmhv_tb_accumulator *acc;
1684
1685                         acc = (struct kvmhv_tb_accumulator *)
1686                                 ((unsigned long)vcpu + timings[i].offset);
1687                         ok = false;
1688                         for (loops = 0; loops < 1000; ++loops) {
1689                                 count = acc->seqcount;
1690                                 if (!(count & 1)) {
1691                                         smp_rmb();
1692                                         tb = *acc;
1693                                         smp_rmb();
1694                                         if (count == acc->seqcount) {
1695                                                 ok = true;
1696                                                 break;
1697                                         }
1698                                 }
1699                                 udelay(1);
1700                         }
1701                         if (!ok)
1702                                 snprintf(s, buf_end - s, "%s: stuck\n",
1703                                         timings[i].name);
1704                         else
1705                                 snprintf(s, buf_end - s,
1706                                         "%s: %llu %llu %llu %llu\n",
1707                                         timings[i].name, count / 2,
1708                                         tb_to_ns(tb.tb_total),
1709                                         tb_to_ns(tb.tb_min),
1710                                         tb_to_ns(tb.tb_max));
1711                         s += strlen(s);
1712                 }
1713                 p->buflen = s - p->buf;
1714         }
1715
1716         pos = *ppos;
1717         if (pos >= p->buflen)
1718                 return 0;
1719         if (len > p->buflen - pos)
1720                 len = p->buflen - pos;
1721         n = copy_to_user(buf, p->buf + pos, len);
1722         if (n) {
1723                 if (n == len)
1724                         return -EFAULT;
1725                 len -= n;
1726         }
1727         *ppos = pos + len;
1728         return len;
1729 }
1730
1731 static ssize_t debugfs_timings_write(struct file *file, const char __user *buf,
1732                                      size_t len, loff_t *ppos)
1733 {
1734         return -EACCES;
1735 }
1736
1737 static const struct file_operations debugfs_timings_ops = {
1738         .owner   = THIS_MODULE,
1739         .open    = debugfs_timings_open,
1740         .release = debugfs_timings_release,
1741         .read    = debugfs_timings_read,
1742         .write   = debugfs_timings_write,
1743         .llseek  = generic_file_llseek,
1744 };
1745
1746 /* Create a debugfs directory for the vcpu */
1747 static void debugfs_vcpu_init(struct kvm_vcpu *vcpu, unsigned int id)
1748 {
1749         char buf[16];
1750         struct kvm *kvm = vcpu->kvm;
1751
1752         snprintf(buf, sizeof(buf), "vcpu%u", id);
1753         if (IS_ERR_OR_NULL(kvm->arch.debugfs_dir))
1754                 return;
1755         vcpu->arch.debugfs_dir = debugfs_create_dir(buf, kvm->arch.debugfs_dir);
1756         if (IS_ERR_OR_NULL(vcpu->arch.debugfs_dir))
1757                 return;
1758         vcpu->arch.debugfs_timings =
1759                 debugfs_create_file("timings", 0444, vcpu->arch.debugfs_dir,
1760                                     vcpu, &debugfs_timings_ops);
1761 }
1762
1763 #else /* CONFIG_KVM_BOOK3S_HV_EXIT_TIMING */
1764 static void debugfs_vcpu_init(struct kvm_vcpu *vcpu, unsigned int id)
1765 {
1766 }
1767 #endif /* CONFIG_KVM_BOOK3S_HV_EXIT_TIMING */
1768
1769 static struct kvm_vcpu *kvmppc_core_vcpu_create_hv(struct kvm *kvm,
1770                                                    unsigned int id)
1771 {
1772         struct kvm_vcpu *vcpu;
1773         int err = -EINVAL;
1774         int core;
1775         struct kvmppc_vcore *vcore;
1776
1777         core = id / threads_per_vcore();
1778         if (core >= KVM_MAX_VCORES)
1779                 goto out;
1780
1781         err = -ENOMEM;
1782         vcpu = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL);
1783         if (!vcpu)
1784                 goto out;
1785
1786         err = kvm_vcpu_init(vcpu, kvm, id);
1787         if (err)
1788                 goto free_vcpu;
1789
1790         vcpu->arch.shared = &vcpu->arch.shregs;
1791 #ifdef CONFIG_KVM_BOOK3S_PR_POSSIBLE
1792         /*
1793          * The shared struct is never shared on HV,
1794          * so we can always use host endianness
1795          */
1796 #ifdef __BIG_ENDIAN__
1797         vcpu->arch.shared_big_endian = true;
1798 #else
1799         vcpu->arch.shared_big_endian = false;
1800 #endif
1801 #endif
1802         vcpu->arch.mmcr[0] = MMCR0_FC;
1803         vcpu->arch.ctrl = CTRL_RUNLATCH;
1804         /* default to host PVR, since we can't spoof it */
1805         kvmppc_set_pvr_hv(vcpu, mfspr(SPRN_PVR));
1806         spin_lock_init(&vcpu->arch.vpa_update_lock);
1807         spin_lock_init(&vcpu->arch.tbacct_lock);
1808         vcpu->arch.busy_preempt = TB_NIL;
1809         vcpu->arch.intr_msr = MSR_SF | MSR_ME;
1810
1811         kvmppc_mmu_book3s_hv_init(vcpu);
1812
1813         vcpu->arch.state = KVMPPC_VCPU_NOTREADY;
1814
1815         init_waitqueue_head(&vcpu->arch.cpu_run);
1816
1817         mutex_lock(&kvm->lock);
1818         vcore = kvm->arch.vcores[core];
1819         if (!vcore) {
1820                 vcore = kvmppc_vcore_create(kvm, core);
1821                 kvm->arch.vcores[core] = vcore;
1822                 kvm->arch.online_vcores++;
1823         }
1824         mutex_unlock(&kvm->lock);
1825
1826         if (!vcore)
1827                 goto free_vcpu;
1828
1829         spin_lock(&vcore->lock);
1830         ++vcore->num_threads;
1831         spin_unlock(&vcore->lock);
1832         vcpu->arch.vcore = vcore;
1833         vcpu->arch.ptid = vcpu->vcpu_id - vcore->first_vcpuid;
1834         vcpu->arch.thread_cpu = -1;
1835         vcpu->arch.prev_cpu = -1;
1836
1837         vcpu->arch.cpu_type = KVM_CPU_3S_64;
1838         kvmppc_sanity_check(vcpu);
1839
1840         debugfs_vcpu_init(vcpu, id);
1841
1842         return vcpu;
1843
1844 free_vcpu:
1845         kmem_cache_free(kvm_vcpu_cache, vcpu);
1846 out:
1847         return ERR_PTR(err);
1848 }
1849
1850 static void unpin_vpa(struct kvm *kvm, struct kvmppc_vpa *vpa)
1851 {
1852         if (vpa->pinned_addr)
1853                 kvmppc_unpin_guest_page(kvm, vpa->pinned_addr, vpa->gpa,
1854                                         vpa->dirty);
1855 }
1856
1857 static void kvmppc_core_vcpu_free_hv(struct kvm_vcpu *vcpu)
1858 {
1859         spin_lock(&vcpu->arch.vpa_update_lock);
1860         unpin_vpa(vcpu->kvm, &vcpu->arch.dtl);
1861         unpin_vpa(vcpu->kvm, &vcpu->arch.slb_shadow);
1862         unpin_vpa(vcpu->kvm, &vcpu->arch.vpa);
1863         spin_unlock(&vcpu->arch.vpa_update_lock);
1864         kvm_vcpu_uninit(vcpu);
1865         kmem_cache_free(kvm_vcpu_cache, vcpu);
1866 }
1867
1868 static int kvmppc_core_check_requests_hv(struct kvm_vcpu *vcpu)
1869 {
1870         /* Indicate we want to get back into the guest */
1871         return 1;
1872 }
1873
1874 static void kvmppc_set_timer(struct kvm_vcpu *vcpu)
1875 {
1876         unsigned long dec_nsec, now;
1877
1878         now = get_tb();
1879         if (now > vcpu->arch.dec_expires) {
1880                 /* decrementer has already gone negative */
1881                 kvmppc_core_queue_dec(vcpu);
1882                 kvmppc_core_prepare_to_enter(vcpu);
1883                 return;
1884         }
1885         dec_nsec = (vcpu->arch.dec_expires - now) * NSEC_PER_SEC
1886                    / tb_ticks_per_sec;
1887         hrtimer_start(&vcpu->arch.dec_timer, dec_nsec, HRTIMER_MODE_REL);
1888         vcpu->arch.timer_running = 1;
1889 }
1890
1891 static void kvmppc_end_cede(struct kvm_vcpu *vcpu)
1892 {
1893         vcpu->arch.ceded = 0;
1894         if (vcpu->arch.timer_running) {
1895                 hrtimer_try_to_cancel(&vcpu->arch.dec_timer);
1896                 vcpu->arch.timer_running = 0;
1897         }
1898 }
1899
1900 extern void __kvmppc_vcore_entry(void);
1901
1902 static void kvmppc_remove_runnable(struct kvmppc_vcore *vc,
1903                                    struct kvm_vcpu *vcpu)
1904 {
1905         u64 now;
1906
1907         if (vcpu->arch.state != KVMPPC_VCPU_RUNNABLE)
1908                 return;
1909         spin_lock_irq(&vcpu->arch.tbacct_lock);
1910         now = mftb();
1911         vcpu->arch.busy_stolen += vcore_stolen_time(vc, now) -
1912                 vcpu->arch.stolen_logged;
1913         vcpu->arch.busy_preempt = now;
1914         vcpu->arch.state = KVMPPC_VCPU_BUSY_IN_HOST;
1915         spin_unlock_irq(&vcpu->arch.tbacct_lock);
1916         --vc->n_runnable;
1917         WRITE_ONCE(vc->runnable_threads[vcpu->arch.ptid], NULL);
1918 }
1919
1920 static int kvmppc_grab_hwthread(int cpu)
1921 {
1922         struct paca_struct *tpaca;
1923         long timeout = 10000;
1924
1925         tpaca = &paca[cpu];
1926
1927         /* Ensure the thread won't go into the kernel if it wakes */
1928         tpaca->kvm_hstate.kvm_vcpu = NULL;
1929         tpaca->kvm_hstate.kvm_vcore = NULL;
1930         tpaca->kvm_hstate.napping = 0;
1931         smp_wmb();
1932         tpaca->kvm_hstate.hwthread_req = 1;
1933
1934         /*
1935          * If the thread is already executing in the kernel (e.g. handling
1936          * a stray interrupt), wait for it to get back to nap mode.
1937          * The smp_mb() is to ensure that our setting of hwthread_req
1938          * is visible before we look at hwthread_state, so if this
1939          * races with the code at system_reset_pSeries and the thread
1940          * misses our setting of hwthread_req, we are sure to see its
1941          * setting of hwthread_state, and vice versa.
1942          */
1943         smp_mb();
1944         while (tpaca->kvm_hstate.hwthread_state == KVM_HWTHREAD_IN_KERNEL) {
1945                 if (--timeout <= 0) {
1946                         pr_err("KVM: couldn't grab cpu %d\n", cpu);
1947                         return -EBUSY;
1948                 }
1949                 udelay(1);
1950         }
1951         return 0;
1952 }
1953
1954 static void kvmppc_release_hwthread(int cpu)
1955 {
1956         struct paca_struct *tpaca;
1957
1958         tpaca = &paca[cpu];
1959         tpaca->kvm_hstate.hwthread_req = 0;
1960         tpaca->kvm_hstate.kvm_vcpu = NULL;
1961         tpaca->kvm_hstate.kvm_vcore = NULL;
1962         tpaca->kvm_hstate.kvm_split_mode = NULL;
1963 }
1964
1965 static void do_nothing(void *x)
1966 {
1967 }
1968
1969 static void radix_flush_cpu(struct kvm *kvm, int cpu, struct kvm_vcpu *vcpu)
1970 {
1971         int i;
1972
1973         cpu = cpu_first_thread_sibling(cpu);
1974         cpumask_set_cpu(cpu, &kvm->arch.need_tlb_flush);
1975         /*
1976          * Make sure setting of bit in need_tlb_flush precedes
1977          * testing of cpu_in_guest bits.  The matching barrier on
1978          * the other side is the first smp_mb() in kvmppc_run_core().
1979          */
1980         smp_mb();
1981         for (i = 0; i < threads_per_core; ++i)
1982                 if (cpumask_test_cpu(cpu + i, &kvm->arch.cpu_in_guest))
1983                         smp_call_function_single(cpu + i, do_nothing, NULL, 1);
1984 }
1985
1986 static void kvmppc_start_thread(struct kvm_vcpu *vcpu, struct kvmppc_vcore *vc)
1987 {
1988         int cpu;
1989         struct paca_struct *tpaca;
1990         struct kvmppc_vcore *mvc = vc->master_vcore;
1991         struct kvm *kvm = vc->kvm;
1992
1993         cpu = vc->pcpu;
1994         if (vcpu) {
1995                 if (vcpu->arch.timer_running) {
1996                         hrtimer_try_to_cancel(&vcpu->arch.dec_timer);
1997                         vcpu->arch.timer_running = 0;
1998                 }
1999                 cpu += vcpu->arch.ptid;
2000                 vcpu->cpu = mvc->pcpu;
2001                 vcpu->arch.thread_cpu = cpu;
2002
2003                 /*
2004                  * With radix, the guest can do TLB invalidations itself,
2005                  * and it could choose to use the local form (tlbiel) if
2006                  * it is invalidating a translation that has only ever been
2007                  * used on one vcpu.  However, that doesn't mean it has
2008                  * only ever been used on one physical cpu, since vcpus
2009                  * can move around between pcpus.  To cope with this, when
2010                  * a vcpu moves from one pcpu to another, we need to tell
2011                  * any vcpus running on the same core as this vcpu previously
2012                  * ran to flush the TLB.  The TLB is shared between threads,
2013                  * so we use a single bit in .need_tlb_flush for all 4 threads.
2014                  */
2015                 if (kvm_is_radix(kvm) && vcpu->arch.prev_cpu != cpu) {
2016                         if (vcpu->arch.prev_cpu >= 0 &&
2017                             cpu_first_thread_sibling(vcpu->arch.prev_cpu) !=
2018                             cpu_first_thread_sibling(cpu))
2019                                 radix_flush_cpu(kvm, vcpu->arch.prev_cpu, vcpu);
2020                         vcpu->arch.prev_cpu = cpu;
2021                 }
2022                 cpumask_set_cpu(cpu, &kvm->arch.cpu_in_guest);
2023         }
2024         tpaca = &paca[cpu];
2025         tpaca->kvm_hstate.kvm_vcpu = vcpu;
2026         tpaca->kvm_hstate.ptid = cpu - mvc->pcpu;
2027         /* Order stores to hstate.kvm_vcpu etc. before store to kvm_vcore */
2028         smp_wmb();
2029         tpaca->kvm_hstate.kvm_vcore = mvc;
2030         if (cpu != smp_processor_id())
2031                 kvmppc_ipi_thread(cpu);
2032 }
2033
2034 static void kvmppc_wait_for_nap(void)
2035 {
2036         int cpu = smp_processor_id();
2037         int i, loops;
2038         int n_threads = threads_per_vcore();
2039
2040         if (n_threads <= 1)
2041                 return;
2042         for (loops = 0; loops < 1000000; ++loops) {
2043                 /*
2044                  * Check if all threads are finished.
2045                  * We set the vcore pointer when starting a thread
2046                  * and the thread clears it when finished, so we look
2047                  * for any threads that still have a non-NULL vcore ptr.
2048                  */
2049                 for (i = 1; i < n_threads; ++i)
2050                         if (paca[cpu + i].kvm_hstate.kvm_vcore)
2051                                 break;
2052                 if (i == n_threads) {
2053                         HMT_medium();
2054                         return;
2055                 }
2056                 HMT_low();
2057         }
2058         HMT_medium();
2059         for (i = 1; i < n_threads; ++i)
2060                 if (paca[cpu + i].kvm_hstate.kvm_vcore)
2061                         pr_err("KVM: CPU %d seems to be stuck\n", cpu + i);
2062 }
2063
2064 /*
2065  * Check that we are on thread 0 and that any other threads in
2066  * this core are off-line.  Then grab the threads so they can't
2067  * enter the kernel.
2068  */
2069 static int on_primary_thread(void)
2070 {
2071         int cpu = smp_processor_id();
2072         int thr;
2073
2074         /* Are we on a primary subcore? */
2075         if (cpu_thread_in_subcore(cpu))
2076                 return 0;
2077
2078         thr = 0;
2079         while (++thr < threads_per_subcore)
2080                 if (cpu_online(cpu + thr))
2081                         return 0;
2082
2083         /* Grab all hw threads so they can't go into the kernel */
2084         for (thr = 1; thr < threads_per_subcore; ++thr) {
2085                 if (kvmppc_grab_hwthread(cpu + thr)) {
2086                         /* Couldn't grab one; let the others go */
2087                         do {
2088                                 kvmppc_release_hwthread(cpu + thr);
2089                         } while (--thr > 0);
2090                         return 0;
2091                 }
2092         }
2093         return 1;
2094 }
2095
2096 /*
2097  * A list of virtual cores for each physical CPU.
2098  * These are vcores that could run but their runner VCPU tasks are
2099  * (or may be) preempted.
2100  */
2101 struct preempted_vcore_list {
2102         struct list_head        list;
2103         spinlock_t              lock;
2104 };
2105
2106 static DEFINE_PER_CPU(struct preempted_vcore_list, preempted_vcores);
2107
2108 static void init_vcore_lists(void)
2109 {
2110         int cpu;
2111
2112         for_each_possible_cpu(cpu) {
2113                 struct preempted_vcore_list *lp = &per_cpu(preempted_vcores, cpu);
2114                 spin_lock_init(&lp->lock);
2115                 INIT_LIST_HEAD(&lp->list);
2116         }
2117 }
2118
2119 static void kvmppc_vcore_preempt(struct kvmppc_vcore *vc)
2120 {
2121         struct preempted_vcore_list *lp = this_cpu_ptr(&preempted_vcores);
2122
2123         vc->vcore_state = VCORE_PREEMPT;
2124         vc->pcpu = smp_processor_id();
2125         if (vc->num_threads < threads_per_vcore()) {
2126                 spin_lock(&lp->lock);
2127                 list_add_tail(&vc->preempt_list, &lp->list);
2128                 spin_unlock(&lp->lock);
2129         }
2130
2131         /* Start accumulating stolen time */
2132         kvmppc_core_start_stolen(vc);
2133 }
2134
2135 static void kvmppc_vcore_end_preempt(struct kvmppc_vcore *vc)
2136 {
2137         struct preempted_vcore_list *lp;
2138
2139         kvmppc_core_end_stolen(vc);
2140         if (!list_empty(&vc->preempt_list)) {
2141                 lp = &per_cpu(preempted_vcores, vc->pcpu);
2142                 spin_lock(&lp->lock);
2143                 list_del_init(&vc->preempt_list);
2144                 spin_unlock(&lp->lock);
2145         }
2146         vc->vcore_state = VCORE_INACTIVE;
2147 }
2148
2149 /*
2150  * This stores information about the virtual cores currently
2151  * assigned to a physical core.
2152  */
2153 struct core_info {
2154         int             n_subcores;
2155         int             max_subcore_threads;
2156         int             total_threads;
2157         int             subcore_threads[MAX_SUBCORES];
2158         struct kvm      *subcore_vm[MAX_SUBCORES];
2159         struct list_head vcs[MAX_SUBCORES];
2160 };
2161
2162 /*
2163  * This mapping means subcores 0 and 1 can use threads 0-3 and 4-7
2164  * respectively in 2-way micro-threading (split-core) mode.
2165  */
2166 static int subcore_thread_map[MAX_SUBCORES] = { 0, 4, 2, 6 };
2167
2168 static void init_core_info(struct core_info *cip, struct kvmppc_vcore *vc)
2169 {
2170         int sub;
2171
2172         memset(cip, 0, sizeof(*cip));
2173         cip->n_subcores = 1;
2174         cip->max_subcore_threads = vc->num_threads;
2175         cip->total_threads = vc->num_threads;
2176         cip->subcore_threads[0] = vc->num_threads;
2177         cip->subcore_vm[0] = vc->kvm;
2178         for (sub = 0; sub < MAX_SUBCORES; ++sub)
2179                 INIT_LIST_HEAD(&cip->vcs[sub]);
2180         list_add_tail(&vc->preempt_list, &cip->vcs[0]);
2181 }
2182
2183 static bool subcore_config_ok(int n_subcores, int n_threads)
2184 {
2185         /* Can only dynamically split if unsplit to begin with */
2186         if (n_subcores > 1 && threads_per_subcore < MAX_SMT_THREADS)
2187                 return false;
2188         if (n_subcores > MAX_SUBCORES)
2189                 return false;
2190         if (n_subcores > 1) {
2191                 if (!(dynamic_mt_modes & 2))
2192                         n_subcores = 4;
2193                 if (n_subcores > 2 && !(dynamic_mt_modes & 4))
2194                         return false;
2195         }
2196
2197         return n_subcores * roundup_pow_of_two(n_threads) <= MAX_SMT_THREADS;
2198 }
2199
2200 static void init_master_vcore(struct kvmppc_vcore *vc)
2201 {
2202         vc->master_vcore = vc;
2203         vc->entry_exit_map = 0;
2204         vc->in_guest = 0;
2205         vc->napping_threads = 0;
2206         vc->conferring_threads = 0;
2207 }
2208
2209 static bool can_dynamic_split(struct kvmppc_vcore *vc, struct core_info *cip)
2210 {
2211         int n_threads = vc->num_threads;
2212         int sub;
2213
2214         if (!cpu_has_feature(CPU_FTR_ARCH_207S))
2215                 return false;
2216
2217         if (n_threads < cip->max_subcore_threads)
2218                 n_threads = cip->max_subcore_threads;
2219         if (!subcore_config_ok(cip->n_subcores + 1, n_threads))
2220                 return false;
2221         cip->max_subcore_threads = n_threads;
2222
2223         sub = cip->n_subcores;
2224         ++cip->n_subcores;
2225         cip->total_threads += vc->num_threads;
2226         cip->subcore_threads[sub] = vc->num_threads;
2227         cip->subcore_vm[sub] = vc->kvm;
2228         init_master_vcore(vc);
2229         list_move_tail(&vc->preempt_list, &cip->vcs[sub]);
2230
2231         return true;
2232 }
2233
2234 /*
2235  * Work out whether it is possible to piggyback the execution of
2236  * vcore *pvc onto the execution of the other vcores described in *cip.
2237  */
2238 static bool can_piggyback(struct kvmppc_vcore *pvc, struct core_info *cip,
2239                           int target_threads)
2240 {
2241         if (cip->total_threads + pvc->num_threads > target_threads)
2242                 return false;
2243
2244         return can_dynamic_split(pvc, cip);
2245 }
2246
2247 static void prepare_threads(struct kvmppc_vcore *vc)
2248 {
2249         int i;
2250         struct kvm_vcpu *vcpu;
2251
2252         for_each_runnable_thread(i, vcpu, vc) {
2253                 if (signal_pending(vcpu->arch.run_task))
2254                         vcpu->arch.ret = -EINTR;
2255                 else if (vcpu->arch.vpa.update_pending ||
2256                          vcpu->arch.slb_shadow.update_pending ||
2257                          vcpu->arch.dtl.update_pending)
2258                         vcpu->arch.ret = RESUME_GUEST;
2259                 else
2260                         continue;
2261                 kvmppc_remove_runnable(vc, vcpu);
2262                 wake_up(&vcpu->arch.cpu_run);
2263         }
2264 }
2265
2266 static void collect_piggybacks(struct core_info *cip, int target_threads)
2267 {
2268         struct preempted_vcore_list *lp = this_cpu_ptr(&preempted_vcores);
2269         struct kvmppc_vcore *pvc, *vcnext;
2270
2271         spin_lock(&lp->lock);
2272         list_for_each_entry_safe(pvc, vcnext, &lp->list, preempt_list) {
2273                 if (!spin_trylock(&pvc->lock))
2274                         continue;
2275                 prepare_threads(pvc);
2276                 if (!pvc->n_runnable) {
2277                         list_del_init(&pvc->preempt_list);
2278                         if (pvc->runner == NULL) {
2279                                 pvc->vcore_state = VCORE_INACTIVE;
2280                                 kvmppc_core_end_stolen(pvc);
2281                         }
2282                         spin_unlock(&pvc->lock);
2283                         continue;
2284                 }
2285                 if (!can_piggyback(pvc, cip, target_threads)) {
2286                         spin_unlock(&pvc->lock);
2287                         continue;
2288                 }
2289                 kvmppc_core_end_stolen(pvc);
2290                 pvc->vcore_state = VCORE_PIGGYBACK;
2291                 if (cip->total_threads >= target_threads)
2292                         break;
2293         }
2294         spin_unlock(&lp->lock);
2295 }
2296
2297 static void post_guest_process(struct kvmppc_vcore *vc, bool is_master)
2298 {
2299         int still_running = 0, i;
2300         u64 now;
2301         long ret;
2302         struct kvm_vcpu *vcpu;
2303
2304         spin_lock(&vc->lock);
2305         now = get_tb();
2306         for_each_runnable_thread(i, vcpu, vc) {
2307                 /* cancel pending dec exception if dec is positive */
2308                 if (now < vcpu->arch.dec_expires &&
2309                     kvmppc_core_pending_dec(vcpu))
2310                         kvmppc_core_dequeue_dec(vcpu);
2311
2312                 trace_kvm_guest_exit(vcpu);
2313
2314                 ret = RESUME_GUEST;
2315                 if (vcpu->arch.trap)
2316                         ret = kvmppc_handle_exit_hv(vcpu->arch.kvm_run, vcpu,
2317                                                     vcpu->arch.run_task);
2318
2319                 vcpu->arch.ret = ret;
2320                 vcpu->arch.trap = 0;
2321
2322                 if (is_kvmppc_resume_guest(vcpu->arch.ret)) {
2323                         if (vcpu->arch.pending_exceptions)
2324                                 kvmppc_core_prepare_to_enter(vcpu);
2325                         if (vcpu->arch.ceded)
2326                                 kvmppc_set_timer(vcpu);
2327                         else
2328                                 ++still_running;
2329                 } else {
2330                         kvmppc_remove_runnable(vc, vcpu);
2331                         wake_up(&vcpu->arch.cpu_run);
2332                 }
2333         }
2334         list_del_init(&vc->preempt_list);
2335         if (!is_master) {
2336                 if (still_running > 0) {
2337                         kvmppc_vcore_preempt(vc);
2338                 } else if (vc->runner) {
2339                         vc->vcore_state = VCORE_PREEMPT;
2340                         kvmppc_core_start_stolen(vc);
2341                 } else {
2342                         vc->vcore_state = VCORE_INACTIVE;
2343                 }
2344                 if (vc->n_runnable > 0 && vc->runner == NULL) {
2345                         /* make sure there's a candidate runner awake */
2346                         i = -1;
2347                         vcpu = next_runnable_thread(vc, &i);
2348                         wake_up(&vcpu->arch.cpu_run);
2349                 }
2350         }
2351         spin_unlock(&vc->lock);
2352 }
2353
2354 /*
2355  * Clear core from the list of active host cores as we are about to
2356  * enter the guest. Only do this if it is the primary thread of the
2357  * core (not if a subcore) that is entering the guest.
2358  */
2359 static inline int kvmppc_clear_host_core(unsigned int cpu)
2360 {
2361         int core;
2362
2363         if (!kvmppc_host_rm_ops_hv || cpu_thread_in_core(cpu))
2364                 return 0;
2365         /*
2366          * Memory barrier can be omitted here as we will do a smp_wmb()
2367          * later in kvmppc_start_thread and we need ensure that state is
2368          * visible to other CPUs only after we enter guest.
2369          */
2370         core = cpu >> threads_shift;
2371         kvmppc_host_rm_ops_hv->rm_core[core].rm_state.in_host = 0;
2372         return 0;
2373 }
2374
2375 /*
2376  * Advertise this core as an active host core since we exited the guest
2377  * Only need to do this if it is the primary thread of the core that is
2378  * exiting.
2379  */
2380 static inline int kvmppc_set_host_core(unsigned int cpu)
2381 {
2382         int core;
2383
2384         if (!kvmppc_host_rm_ops_hv || cpu_thread_in_core(cpu))
2385                 return 0;
2386
2387         /*
2388          * Memory barrier can be omitted here because we do a spin_unlock
2389          * immediately after this which provides the memory barrier.
2390          */
2391         core = cpu >> threads_shift;
2392         kvmppc_host_rm_ops_hv->rm_core[core].rm_state.in_host = 1;
2393         return 0;
2394 }
2395
2396 /*
2397  * Run a set of guest threads on a physical core.
2398  * Called with vc->lock held.
2399  */
2400 static noinline void kvmppc_run_core(struct kvmppc_vcore *vc)
2401 {
2402         struct kvm_vcpu *vcpu;
2403         int i;
2404         int srcu_idx;
2405         struct core_info core_info;
2406         struct kvmppc_vcore *pvc, *vcnext;
2407         struct kvm_split_mode split_info, *sip;
2408         int split, subcore_size, active;
2409         int sub;
2410         bool thr0_done;
2411         unsigned long cmd_bit, stat_bit;
2412         int pcpu, thr;
2413         int target_threads;
2414         int controlled_threads;
2415
2416         /*
2417          * Remove from the list any threads that have a signal pending
2418          * or need a VPA update done
2419          */
2420         prepare_threads(vc);
2421
2422         /* if the runner is no longer runnable, let the caller pick a new one */
2423         if (vc->runner->arch.state != KVMPPC_VCPU_RUNNABLE)
2424                 return;
2425
2426         /*
2427          * Initialize *vc.
2428          */
2429         init_master_vcore(vc);
2430         vc->preempt_tb = TB_NIL;
2431
2432         /*
2433          * Number of threads that we will be controlling: the same as
2434          * the number of threads per subcore, except on POWER9,
2435          * where it's 1 because the threads are (mostly) independent.
2436          */
2437         controlled_threads = threads_per_vcore();
2438
2439         /*
2440          * Make sure we are running on primary threads, and that secondary
2441          * threads are offline.  Also check if the number of threads in this
2442          * guest are greater than the current system threads per guest.
2443          */
2444         if ((controlled_threads > 1) &&
2445             ((vc->num_threads > threads_per_subcore) || !on_primary_thread())) {
2446                 for_each_runnable_thread(i, vcpu, vc) {
2447                         vcpu->arch.ret = -EBUSY;
2448                         kvmppc_remove_runnable(vc, vcpu);
2449                         wake_up(&vcpu->arch.cpu_run);
2450                 }
2451                 goto out;
2452         }
2453
2454         /*
2455          * See if we could run any other vcores on the physical core
2456          * along with this one.
2457          */
2458         init_core_info(&core_info, vc);
2459         pcpu = smp_processor_id();
2460         target_threads = controlled_threads;
2461         if (target_smt_mode && target_smt_mode < target_threads)
2462                 target_threads = target_smt_mode;
2463         if (vc->num_threads < target_threads)
2464                 collect_piggybacks(&core_info, target_threads);
2465
2466         /* Decide on micro-threading (split-core) mode */
2467         subcore_size = threads_per_subcore;
2468         cmd_bit = stat_bit = 0;
2469         split = core_info.n_subcores;
2470         sip = NULL;
2471         if (split > 1) {
2472                 /* threads_per_subcore must be MAX_SMT_THREADS (8) here */
2473                 if (split == 2 && (dynamic_mt_modes & 2)) {
2474                         cmd_bit = HID0_POWER8_1TO2LPAR;
2475                         stat_bit = HID0_POWER8_2LPARMODE;
2476                 } else {
2477                         split = 4;
2478                         cmd_bit = HID0_POWER8_1TO4LPAR;
2479                         stat_bit = HID0_POWER8_4LPARMODE;
2480                 }
2481                 subcore_size = MAX_SMT_THREADS / split;
2482                 sip = &split_info;
2483                 memset(&split_info, 0, sizeof(split_info));
2484                 split_info.rpr = mfspr(SPRN_RPR);
2485                 split_info.pmmar = mfspr(SPRN_PMMAR);
2486                 split_info.ldbar = mfspr(SPRN_LDBAR);
2487                 split_info.subcore_size = subcore_size;
2488                 for (sub = 0; sub < core_info.n_subcores; ++sub)
2489                         split_info.master_vcs[sub] =
2490                                 list_first_entry(&core_info.vcs[sub],
2491                                         struct kvmppc_vcore, preempt_list);
2492                 /* order writes to split_info before kvm_split_mode pointer */
2493                 smp_wmb();
2494         }
2495         pcpu = smp_processor_id();
2496         for (thr = 0; thr < controlled_threads; ++thr)
2497                 paca[pcpu + thr].kvm_hstate.kvm_split_mode = sip;
2498
2499         /* Initiate micro-threading (split-core) if required */
2500         if (cmd_bit) {
2501                 unsigned long hid0 = mfspr(SPRN_HID0);
2502
2503                 hid0 |= cmd_bit | HID0_POWER8_DYNLPARDIS;
2504                 mb();
2505                 mtspr(SPRN_HID0, hid0);
2506                 isync();
2507                 for (;;) {
2508                         hid0 = mfspr(SPRN_HID0);
2509                         if (hid0 & stat_bit)
2510                                 break;
2511                         cpu_relax();
2512                 }
2513         }
2514
2515         kvmppc_clear_host_core(pcpu);
2516
2517         /* Start all the threads */
2518         active = 0;
2519         for (sub = 0; sub < core_info.n_subcores; ++sub) {
2520                 thr = subcore_thread_map[sub];
2521                 thr0_done = false;
2522                 active |= 1 << thr;
2523                 list_for_each_entry(pvc, &core_info.vcs[sub], preempt_list) {
2524                         pvc->pcpu = pcpu + thr;
2525                         for_each_runnable_thread(i, vcpu, pvc) {
2526                                 kvmppc_start_thread(vcpu, pvc);
2527                                 kvmppc_create_dtl_entry(vcpu, pvc);
2528                                 trace_kvm_guest_enter(vcpu);
2529                                 if (!vcpu->arch.ptid)
2530                                         thr0_done = true;
2531                                 active |= 1 << (thr + vcpu->arch.ptid);
2532                         }
2533                         /*
2534                          * We need to start the first thread of each subcore
2535                          * even if it doesn't have a vcpu.
2536                          */
2537                         if (pvc->master_vcore == pvc && !thr0_done)
2538                                 kvmppc_start_thread(NULL, pvc);
2539                         thr += pvc->num_threads;
2540                 }
2541         }
2542
2543         /*
2544          * Ensure that split_info.do_nap is set after setting
2545          * the vcore pointer in the PACA of the secondaries.
2546          */
2547         smp_mb();
2548         if (cmd_bit)
2549                 split_info.do_nap = 1;  /* ask secondaries to nap when done */
2550
2551         /*
2552          * When doing micro-threading, poke the inactive threads as well.
2553          * This gets them to the nap instruction after kvm_do_nap,
2554          * which reduces the time taken to unsplit later.
2555          */
2556         if (split > 1)
2557                 for (thr = 1; thr < threads_per_subcore; ++thr)
2558                         if (!(active & (1 << thr)))
2559                                 kvmppc_ipi_thread(pcpu + thr);
2560
2561         vc->vcore_state = VCORE_RUNNING;
2562         preempt_disable();
2563
2564         trace_kvmppc_run_core(vc, 0);
2565
2566         for (sub = 0; sub < core_info.n_subcores; ++sub)
2567                 list_for_each_entry(pvc, &core_info.vcs[sub], preempt_list)
2568                         spin_unlock(&pvc->lock);
2569
2570         guest_enter();
2571
2572         srcu_idx = srcu_read_lock(&vc->kvm->srcu);
2573
2574         __kvmppc_vcore_entry();
2575
2576         srcu_read_unlock(&vc->kvm->srcu, srcu_idx);
2577
2578         spin_lock(&vc->lock);
2579         /* prevent other vcpu threads from doing kvmppc_start_thread() now */
2580         vc->vcore_state = VCORE_EXITING;
2581
2582         /* wait for secondary threads to finish writing their state to memory */
2583         kvmppc_wait_for_nap();
2584
2585         /* Return to whole-core mode if we split the core earlier */
2586         if (split > 1) {
2587                 unsigned long hid0 = mfspr(SPRN_HID0);
2588                 unsigned long loops = 0;
2589
2590                 hid0 &= ~HID0_POWER8_DYNLPARDIS;
2591                 stat_bit = HID0_POWER8_2LPARMODE | HID0_POWER8_4LPARMODE;
2592                 mb();
2593                 mtspr(SPRN_HID0, hid0);
2594                 isync();
2595                 for (;;) {
2596                         hid0 = mfspr(SPRN_HID0);
2597                         if (!(hid0 & stat_bit))
2598                                 break;
2599                         cpu_relax();
2600                         ++loops;
2601                 }
2602                 split_info.do_nap = 0;
2603         }
2604
2605         /* Let secondaries go back to the offline loop */
2606         for (i = 0; i < controlled_threads; ++i) {
2607                 kvmppc_release_hwthread(pcpu + i);
2608                 if (sip && sip->napped[i])
2609                         kvmppc_ipi_thread(pcpu + i);
2610                 cpumask_clear_cpu(pcpu + i, &vc->kvm->arch.cpu_in_guest);
2611         }
2612
2613         kvmppc_set_host_core(pcpu);
2614
2615         spin_unlock(&vc->lock);
2616
2617         /* make sure updates to secondary vcpu structs are visible now */
2618         smp_mb();
2619         guest_exit();
2620
2621         for (sub = 0; sub < core_info.n_subcores; ++sub)
2622                 list_for_each_entry_safe(pvc, vcnext, &core_info.vcs[sub],
2623                                          preempt_list)
2624                         post_guest_process(pvc, pvc == vc);
2625
2626         spin_lock(&vc->lock);
2627         preempt_enable();
2628
2629  out:
2630         vc->vcore_state = VCORE_INACTIVE;
2631         trace_kvmppc_run_core(vc, 1);
2632 }
2633
2634 /*
2635  * Wait for some other vcpu thread to execute us, and
2636  * wake us up when we need to handle something in the host.
2637  */
2638 static void kvmppc_wait_for_exec(struct kvmppc_vcore *vc,
2639                                  struct kvm_vcpu *vcpu, int wait_state)
2640 {
2641         DEFINE_WAIT(wait);
2642
2643         prepare_to_wait(&vcpu->arch.cpu_run, &wait, wait_state);
2644         if (vcpu->arch.state == KVMPPC_VCPU_RUNNABLE) {
2645                 spin_unlock(&vc->lock);
2646                 schedule();
2647                 spin_lock(&vc->lock);
2648         }
2649         finish_wait(&vcpu->arch.cpu_run, &wait);
2650 }
2651
2652 static void grow_halt_poll_ns(struct kvmppc_vcore *vc)
2653 {
2654         /* 10us base */
2655         if (vc->halt_poll_ns == 0 && halt_poll_ns_grow)
2656                 vc->halt_poll_ns = 10000;
2657         else
2658                 vc->halt_poll_ns *= halt_poll_ns_grow;
2659 }
2660
2661 static void shrink_halt_poll_ns(struct kvmppc_vcore *vc)
2662 {
2663         if (halt_poll_ns_shrink == 0)
2664                 vc->halt_poll_ns = 0;
2665         else
2666                 vc->halt_poll_ns /= halt_poll_ns_shrink;
2667 }
2668
2669 /*
2670  * Check to see if any of the runnable vcpus on the vcore have pending
2671  * exceptions or are no longer ceded
2672  */
2673 static int kvmppc_vcore_check_block(struct kvmppc_vcore *vc)
2674 {
2675         struct kvm_vcpu *vcpu;
2676         int i;
2677
2678         for_each_runnable_thread(i, vcpu, vc) {
2679                 if (vcpu->arch.pending_exceptions || !vcpu->arch.ceded ||
2680                     vcpu->arch.prodded)
2681                         return 1;
2682         }
2683
2684         return 0;
2685 }
2686
2687 /*
2688  * All the vcpus in this vcore are idle, so wait for a decrementer
2689  * or external interrupt to one of the vcpus.  vc->lock is held.
2690  */
2691 static void kvmppc_vcore_blocked(struct kvmppc_vcore *vc)
2692 {
2693         ktime_t cur, start_poll, start_wait;
2694         int do_sleep = 1;
2695         u64 block_ns;
2696         DECLARE_SWAITQUEUE(wait);
2697
2698         /* Poll for pending exceptions and ceded state */
2699         cur = start_poll = ktime_get();
2700         if (vc->halt_poll_ns) {
2701                 ktime_t stop = ktime_add_ns(start_poll, vc->halt_poll_ns);
2702                 ++vc->runner->stat.halt_attempted_poll;
2703
2704                 vc->vcore_state = VCORE_POLLING;
2705                 spin_unlock(&vc->lock);
2706
2707                 do {
2708                         if (kvmppc_vcore_check_block(vc)) {
2709                                 do_sleep = 0;
2710                                 break;
2711                         }
2712                         cur = ktime_get();
2713                 } while (single_task_running() && ktime_before(cur, stop));
2714
2715                 spin_lock(&vc->lock);
2716                 vc->vcore_state = VCORE_INACTIVE;
2717
2718                 if (!do_sleep) {
2719                         ++vc->runner->stat.halt_successful_poll;
2720                         goto out;
2721                 }
2722         }
2723
2724         prepare_to_swait(&vc->wq, &wait, TASK_INTERRUPTIBLE);
2725
2726         if (kvmppc_vcore_check_block(vc)) {
2727                 finish_swait(&vc->wq, &wait);
2728                 do_sleep = 0;
2729                 /* If we polled, count this as a successful poll */
2730                 if (vc->halt_poll_ns)
2731                         ++vc->runner->stat.halt_successful_poll;
2732                 goto out;
2733         }
2734
2735         start_wait = ktime_get();
2736
2737         vc->vcore_state = VCORE_SLEEPING;
2738         trace_kvmppc_vcore_blocked(vc, 0);
2739         spin_unlock(&vc->lock);
2740         schedule();
2741         finish_swait(&vc->wq, &wait);
2742         spin_lock(&vc->lock);
2743         vc->vcore_state = VCORE_INACTIVE;
2744         trace_kvmppc_vcore_blocked(vc, 1);
2745         ++vc->runner->stat.halt_successful_wait;
2746
2747         cur = ktime_get();
2748
2749 out:
2750         block_ns = ktime_to_ns(cur) - ktime_to_ns(start_poll);
2751
2752         /* Attribute wait time */
2753         if (do_sleep) {
2754                 vc->runner->stat.halt_wait_ns +=
2755                         ktime_to_ns(cur) - ktime_to_ns(start_wait);
2756                 /* Attribute failed poll time */
2757                 if (vc->halt_poll_ns)
2758                         vc->runner->stat.halt_poll_fail_ns +=
2759                                 ktime_to_ns(start_wait) -
2760                                 ktime_to_ns(start_poll);
2761         } else {
2762                 /* Attribute successful poll time */
2763                 if (vc->halt_poll_ns)
2764                         vc->runner->stat.halt_poll_success_ns +=
2765                                 ktime_to_ns(cur) -
2766                                 ktime_to_ns(start_poll);
2767         }
2768
2769         /* Adjust poll time */
2770         if (halt_poll_ns) {
2771                 if (block_ns <= vc->halt_poll_ns)
2772                         ;
2773                 /* We slept and blocked for longer than the max halt time */
2774                 else if (vc->halt_poll_ns && block_ns > halt_poll_ns)
2775                         shrink_halt_poll_ns(vc);
2776                 /* We slept and our poll time is too small */
2777                 else if (vc->halt_poll_ns < halt_poll_ns &&
2778                                 block_ns < halt_poll_ns)
2779                         grow_halt_poll_ns(vc);
2780                 if (vc->halt_poll_ns > halt_poll_ns)
2781                         vc->halt_poll_ns = halt_poll_ns;
2782         } else
2783                 vc->halt_poll_ns = 0;
2784
2785         trace_kvmppc_vcore_wakeup(do_sleep, block_ns);
2786 }
2787
2788 static int kvmppc_run_vcpu(struct kvm_run *kvm_run, struct kvm_vcpu *vcpu)
2789 {
2790         int n_ceded, i;
2791         struct kvmppc_vcore *vc;
2792         struct kvm_vcpu *v;
2793
2794         trace_kvmppc_run_vcpu_enter(vcpu);
2795
2796         kvm_run->exit_reason = 0;
2797         vcpu->arch.ret = RESUME_GUEST;
2798         vcpu->arch.trap = 0;
2799         kvmppc_update_vpas(vcpu);
2800
2801         /*
2802          * Synchronize with other threads in this virtual core
2803          */
2804         vc = vcpu->arch.vcore;
2805         spin_lock(&vc->lock);
2806         vcpu->arch.ceded = 0;
2807         vcpu->arch.run_task = current;
2808         vcpu->arch.kvm_run = kvm_run;
2809         vcpu->arch.stolen_logged = vcore_stolen_time(vc, mftb());
2810         vcpu->arch.state = KVMPPC_VCPU_RUNNABLE;
2811         vcpu->arch.busy_preempt = TB_NIL;
2812         WRITE_ONCE(vc->runnable_threads[vcpu->arch.ptid], vcpu);
2813         ++vc->n_runnable;
2814
2815         /*
2816          * This happens the first time this is called for a vcpu.
2817          * If the vcore is already running, we may be able to start
2818          * this thread straight away and have it join in.
2819          */
2820         if (!signal_pending(current)) {
2821                 if (vc->vcore_state == VCORE_PIGGYBACK) {
2822                         struct kvmppc_vcore *mvc = vc->master_vcore;
2823                         if (spin_trylock(&mvc->lock)) {
2824                                 if (mvc->vcore_state == VCORE_RUNNING &&
2825                                     !VCORE_IS_EXITING(mvc)) {
2826                                         kvmppc_create_dtl_entry(vcpu, vc);
2827                                         kvmppc_start_thread(vcpu, vc);
2828                                         trace_kvm_guest_enter(vcpu);
2829                                 }
2830                                 spin_unlock(&mvc->lock);
2831                         }
2832                 } else if (vc->vcore_state == VCORE_RUNNING &&
2833                            !VCORE_IS_EXITING(vc)) {
2834                         kvmppc_create_dtl_entry(vcpu, vc);
2835                         kvmppc_start_thread(vcpu, vc);
2836                         trace_kvm_guest_enter(vcpu);
2837                 } else if (vc->vcore_state == VCORE_SLEEPING) {
2838                         swake_up(&vc->wq);
2839                 }
2840
2841         }
2842
2843         while (vcpu->arch.state == KVMPPC_VCPU_RUNNABLE &&
2844                !signal_pending(current)) {
2845                 if (vc->vcore_state == VCORE_PREEMPT && vc->runner == NULL)
2846                         kvmppc_vcore_end_preempt(vc);
2847
2848                 if (vc->vcore_state != VCORE_INACTIVE) {
2849                         kvmppc_wait_for_exec(vc, vcpu, TASK_INTERRUPTIBLE);
2850                         continue;
2851                 }
2852                 for_each_runnable_thread(i, v, vc) {
2853                         kvmppc_core_prepare_to_enter(v);
2854                         if (signal_pending(v->arch.run_task)) {
2855                                 kvmppc_remove_runnable(vc, v);
2856                                 v->stat.signal_exits++;
2857                                 v->arch.kvm_run->exit_reason = KVM_EXIT_INTR;
2858                                 v->arch.ret = -EINTR;
2859                                 wake_up(&v->arch.cpu_run);
2860                         }
2861                 }
2862                 if (!vc->n_runnable || vcpu->arch.state != KVMPPC_VCPU_RUNNABLE)
2863                         break;
2864                 n_ceded = 0;
2865                 for_each_runnable_thread(i, v, vc) {
2866                         if (!v->arch.pending_exceptions && !v->arch.prodded)
2867                                 n_ceded += v->arch.ceded;
2868                         else
2869                                 v->arch.ceded = 0;
2870                 }
2871                 vc->runner = vcpu;
2872                 if (n_ceded == vc->n_runnable) {
2873                         kvmppc_vcore_blocked(vc);
2874                 } else if (need_resched()) {
2875                         kvmppc_vcore_preempt(vc);
2876                         /* Let something else run */
2877                         cond_resched_lock(&vc->lock);
2878                         if (vc->vcore_state == VCORE_PREEMPT)
2879                                 kvmppc_vcore_end_preempt(vc);
2880                 } else {
2881                         kvmppc_run_core(vc);
2882                 }
2883                 vc->runner = NULL;
2884         }
2885
2886         while (vcpu->arch.state == KVMPPC_VCPU_RUNNABLE &&
2887                (vc->vcore_state == VCORE_RUNNING ||
2888                 vc->vcore_state == VCORE_EXITING ||
2889                 vc->vcore_state == VCORE_PIGGYBACK))
2890                 kvmppc_wait_for_exec(vc, vcpu, TASK_UNINTERRUPTIBLE);
2891
2892         if (vc->vcore_state == VCORE_PREEMPT && vc->runner == NULL)
2893                 kvmppc_vcore_end_preempt(vc);
2894
2895         if (vcpu->arch.state == KVMPPC_VCPU_RUNNABLE) {
2896                 kvmppc_remove_runnable(vc, vcpu);
2897                 vcpu->stat.signal_exits++;
2898                 kvm_run->exit_reason = KVM_EXIT_INTR;
2899                 vcpu->arch.ret = -EINTR;
2900         }
2901
2902         if (vc->n_runnable && vc->vcore_state == VCORE_INACTIVE) {
2903                 /* Wake up some vcpu to run the core */
2904                 i = -1;
2905                 v = next_runnable_thread(vc, &i);
2906                 wake_up(&v->arch.cpu_run);
2907         }
2908
2909         trace_kvmppc_run_vcpu_exit(vcpu, kvm_run);
2910         spin_unlock(&vc->lock);
2911         return vcpu->arch.ret;
2912 }
2913
2914 static int kvmppc_vcpu_run_hv(struct kvm_run *run, struct kvm_vcpu *vcpu)
2915 {
2916         int r;
2917         int srcu_idx;
2918         unsigned long ebb_regs[3] = {}; /* shut up GCC */
2919         unsigned long user_tar = 0;
2920         unsigned int user_vrsave;
2921
2922         if (!vcpu->arch.sane) {
2923                 run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
2924                 return -EINVAL;
2925         }
2926
2927         /*
2928          * Don't allow entry with a suspended transaction, because
2929          * the guest entry/exit code will lose it.
2930          * If the guest has TM enabled, save away their TM-related SPRs
2931          * (they will get restored by the TM unavailable interrupt).
2932          */
2933 #ifdef CONFIG_PPC_TRANSACTIONAL_MEM
2934         if (cpu_has_feature(CPU_FTR_TM) && current->thread.regs &&
2935             (current->thread.regs->msr & MSR_TM)) {
2936                 if (MSR_TM_ACTIVE(current->thread.regs->msr)) {
2937                         run->exit_reason = KVM_EXIT_FAIL_ENTRY;
2938                         run->fail_entry.hardware_entry_failure_reason = 0;
2939                         return -EINVAL;
2940                 }
2941                 current->thread.tm_tfhar = mfspr(SPRN_TFHAR);
2942                 current->thread.tm_tfiar = mfspr(SPRN_TFIAR);
2943                 current->thread.tm_texasr = mfspr(SPRN_TEXASR);
2944                 current->thread.regs->msr &= ~MSR_TM;
2945         }
2946 #endif
2947
2948         kvmppc_core_prepare_to_enter(vcpu);
2949
2950         /* No need to go into the guest when all we'll do is come back out */
2951         if (signal_pending(current)) {
2952                 run->exit_reason = KVM_EXIT_INTR;
2953                 return -EINTR;
2954         }
2955
2956         atomic_inc(&vcpu->kvm->arch.vcpus_running);
2957         /* Order vcpus_running vs. hpte_setup_done, see kvmppc_alloc_reset_hpt */
2958         smp_mb();
2959
2960         /* On the first time here, set up HTAB and VRMA */
2961         if (!kvm_is_radix(vcpu->kvm) && !vcpu->kvm->arch.hpte_setup_done) {
2962                 r = kvmppc_hv_setup_htab_rma(vcpu);
2963                 if (r)
2964                         goto out;
2965         }
2966
2967         flush_all_to_thread(current);
2968
2969         /* Save userspace EBB and other register values */
2970         if (cpu_has_feature(CPU_FTR_ARCH_207S)) {
2971                 ebb_regs[0] = mfspr(SPRN_EBBHR);
2972                 ebb_regs[1] = mfspr(SPRN_EBBRR);
2973                 ebb_regs[2] = mfspr(SPRN_BESCR);
2974                 user_tar = mfspr(SPRN_TAR);
2975         }
2976         user_vrsave = mfspr(SPRN_VRSAVE);
2977
2978         vcpu->arch.wqp = &vcpu->arch.vcore->wq;
2979         vcpu->arch.pgdir = current->mm->pgd;
2980         vcpu->arch.state = KVMPPC_VCPU_BUSY_IN_HOST;
2981
2982         do {
2983                 r = kvmppc_run_vcpu(run, vcpu);
2984
2985                 if (run->exit_reason == KVM_EXIT_PAPR_HCALL &&
2986                     !(vcpu->arch.shregs.msr & MSR_PR)) {
2987                         trace_kvm_hcall_enter(vcpu);
2988                         r = kvmppc_pseries_do_hcall(vcpu);
2989                         trace_kvm_hcall_exit(vcpu, r);
2990                         kvmppc_core_prepare_to_enter(vcpu);
2991                 } else if (r == RESUME_PAGE_FAULT) {
2992                         srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
2993                         r = kvmppc_book3s_hv_page_fault(run, vcpu,
2994                                 vcpu->arch.fault_dar, vcpu->arch.fault_dsisr);
2995                         srcu_read_unlock(&vcpu->kvm->srcu, srcu_idx);
2996                 } else if (r == RESUME_PASSTHROUGH) {
2997                         if (WARN_ON(xive_enabled()))
2998                                 r = H_SUCCESS;
2999                         else
3000                                 r = kvmppc_xics_rm_complete(vcpu, 0);
3001                 }
3002         } while (is_kvmppc_resume_guest(r));
3003
3004         /* Restore userspace EBB and other register values */
3005         if (cpu_has_feature(CPU_FTR_ARCH_207S)) {
3006                 mtspr(SPRN_EBBHR, ebb_regs[0]);
3007                 mtspr(SPRN_EBBRR, ebb_regs[1]);
3008                 mtspr(SPRN_BESCR, ebb_regs[2]);
3009                 mtspr(SPRN_TAR, user_tar);
3010                 mtspr(SPRN_FSCR, current->thread.fscr);
3011         }
3012         mtspr(SPRN_VRSAVE, user_vrsave);
3013
3014  out:
3015         vcpu->arch.state = KVMPPC_VCPU_NOTREADY;
3016         atomic_dec(&vcpu->kvm->arch.vcpus_running);
3017         return r;
3018 }
3019
3020 static void kvmppc_add_seg_page_size(struct kvm_ppc_one_seg_page_size **sps,
3021                                      int linux_psize)
3022 {
3023         struct mmu_psize_def *def = &mmu_psize_defs[linux_psize];
3024
3025         if (!def->shift)
3026                 return;
3027         (*sps)->page_shift = def->shift;
3028         (*sps)->slb_enc = def->sllp;
3029         (*sps)->enc[0].page_shift = def->shift;
3030         (*sps)->enc[0].pte_enc = def->penc[linux_psize];
3031         /*
3032          * Add 16MB MPSS support if host supports it
3033          */
3034         if (linux_psize != MMU_PAGE_16M && def->penc[MMU_PAGE_16M] != -1) {
3035                 (*sps)->enc[1].page_shift = 24;
3036                 (*sps)->enc[1].pte_enc = def->penc[MMU_PAGE_16M];
3037         }
3038         (*sps)++;
3039 }
3040
3041 static int kvm_vm_ioctl_get_smmu_info_hv(struct kvm *kvm,
3042                                          struct kvm_ppc_smmu_info *info)
3043 {
3044         struct kvm_ppc_one_seg_page_size *sps;
3045
3046         /*
3047          * Since we don't yet support HPT guests on a radix host,
3048          * return an error if the host uses radix.
3049          */
3050         if (radix_enabled())
3051                 return -EINVAL;
3052
3053         info->flags = KVM_PPC_PAGE_SIZES_REAL;
3054         if (mmu_has_feature(MMU_FTR_1T_SEGMENT))
3055                 info->flags |= KVM_PPC_1T_SEGMENTS;
3056         info->slb_size = mmu_slb_size;
3057
3058         /* We only support these sizes for now, and no muti-size segments */
3059         sps = &info->sps[0];
3060         kvmppc_add_seg_page_size(&sps, MMU_PAGE_4K);
3061         kvmppc_add_seg_page_size(&sps, MMU_PAGE_64K);
3062         kvmppc_add_seg_page_size(&sps, MMU_PAGE_16M);
3063
3064         return 0;
3065 }
3066
3067 /*
3068  * Get (and clear) the dirty memory log for a memory slot.
3069  */
3070 static int kvm_vm_ioctl_get_dirty_log_hv(struct kvm *kvm,
3071                                          struct kvm_dirty_log *log)
3072 {
3073         struct kvm_memslots *slots;
3074         struct kvm_memory_slot *memslot;
3075         int i, r;
3076         unsigned long n;
3077         unsigned long *buf;
3078         struct kvm_vcpu *vcpu;
3079
3080         mutex_lock(&kvm->slots_lock);
3081
3082         r = -EINVAL;
3083         if (log->slot >= KVM_USER_MEM_SLOTS)
3084                 goto out;
3085
3086         slots = kvm_memslots(kvm);
3087         memslot = id_to_memslot(slots, log->slot);
3088         r = -ENOENT;
3089         if (!memslot->dirty_bitmap)
3090                 goto out;
3091
3092         /*
3093          * Use second half of bitmap area because radix accumulates
3094          * bits in the first half.
3095          */
3096         n = kvm_dirty_bitmap_bytes(memslot);
3097         buf = memslot->dirty_bitmap + n / sizeof(long);
3098         memset(buf, 0, n);
3099
3100         if (kvm_is_radix(kvm))
3101                 r = kvmppc_hv_get_dirty_log_radix(kvm, memslot, buf);
3102         else
3103                 r = kvmppc_hv_get_dirty_log_hpt(kvm, memslot, buf);
3104         if (r)
3105                 goto out;
3106
3107         /* Harvest dirty bits from VPA and DTL updates */
3108         /* Note: we never modify the SLB shadow buffer areas */
3109         kvm_for_each_vcpu(i, vcpu, kvm) {
3110                 spin_lock(&vcpu->arch.vpa_update_lock);
3111                 kvmppc_harvest_vpa_dirty(&vcpu->arch.vpa, memslot, buf);
3112                 kvmppc_harvest_vpa_dirty(&vcpu->arch.dtl, memslot, buf);
3113                 spin_unlock(&vcpu->arch.vpa_update_lock);
3114         }
3115
3116         r = -EFAULT;
3117         if (copy_to_user(log->dirty_bitmap, buf, n))
3118                 goto out;
3119
3120         r = 0;
3121 out:
3122         mutex_unlock(&kvm->slots_lock);
3123         return r;
3124 }
3125
3126 static void kvmppc_core_free_memslot_hv(struct kvm_memory_slot *free,
3127                                         struct kvm_memory_slot *dont)
3128 {
3129         if (!dont || free->arch.rmap != dont->arch.rmap) {
3130                 vfree(free->arch.rmap);
3131                 free->arch.rmap = NULL;
3132         }
3133 }
3134
3135 static int kvmppc_core_create_memslot_hv(struct kvm_memory_slot *slot,
3136                                          unsigned long npages)
3137 {
3138         /*
3139          * For now, if radix_enabled() then we only support radix guests,
3140          * and in that case we don't need the rmap array.
3141          */
3142         if (radix_enabled()) {
3143                 slot->arch.rmap = NULL;
3144                 return 0;
3145         }
3146
3147         slot->arch.rmap = vzalloc(npages * sizeof(*slot->arch.rmap));
3148         if (!slot->arch.rmap)
3149                 return -ENOMEM;
3150
3151         return 0;
3152 }
3153
3154 static int kvmppc_core_prepare_memory_region_hv(struct kvm *kvm,
3155                                         struct kvm_memory_slot *memslot,
3156                                         const struct kvm_userspace_memory_region *mem)
3157 {
3158         return 0;
3159 }
3160
3161 static void kvmppc_core_commit_memory_region_hv(struct kvm *kvm,
3162                                 const struct kvm_userspace_memory_region *mem,
3163                                 const struct kvm_memory_slot *old,
3164                                 const struct kvm_memory_slot *new)
3165 {
3166         unsigned long npages = mem->memory_size >> PAGE_SHIFT;
3167         struct kvm_memslots *slots;
3168         struct kvm_memory_slot *memslot;
3169
3170         /*
3171          * If we are making a new memslot, it might make
3172          * some address that was previously cached as emulated
3173          * MMIO be no longer emulated MMIO, so invalidate
3174          * all the caches of emulated MMIO translations.
3175          */
3176         if (npages)
3177                 atomic64_inc(&kvm->arch.mmio_update);
3178
3179         if (npages && old->npages && !kvm_is_radix(kvm)) {
3180                 /*
3181                  * If modifying a memslot, reset all the rmap dirty bits.
3182                  * If this is a new memslot, we don't need to do anything
3183                  * since the rmap array starts out as all zeroes,
3184                  * i.e. no pages are dirty.
3185                  */
3186                 slots = kvm_memslots(kvm);
3187                 memslot = id_to_memslot(slots, mem->slot);
3188                 kvmppc_hv_get_dirty_log_hpt(kvm, memslot, NULL);
3189         }
3190 }
3191
3192 /*
3193  * Update LPCR values in kvm->arch and in vcores.
3194  * Caller must hold kvm->lock.
3195  */
3196 void kvmppc_update_lpcr(struct kvm *kvm, unsigned long lpcr, unsigned long mask)
3197 {
3198         long int i;
3199         u32 cores_done = 0;
3200
3201         if ((kvm->arch.lpcr & mask) == lpcr)
3202                 return;
3203
3204         kvm->arch.lpcr = (kvm->arch.lpcr & ~mask) | lpcr;
3205
3206         for (i = 0; i < KVM_MAX_VCORES; ++i) {
3207                 struct kvmppc_vcore *vc = kvm->arch.vcores[i];
3208                 if (!vc)
3209                         continue;
3210                 spin_lock(&vc->lock);
3211                 vc->lpcr = (vc->lpcr & ~mask) | lpcr;
3212                 spin_unlock(&vc->lock);
3213                 if (++cores_done >= kvm->arch.online_vcores)
3214                         break;
3215         }
3216 }
3217
3218 static void kvmppc_mmu_destroy_hv(struct kvm_vcpu *vcpu)
3219 {
3220         return;
3221 }
3222
3223 static void kvmppc_setup_partition_table(struct kvm *kvm)
3224 {
3225         unsigned long dw0, dw1;
3226
3227         if (!kvm_is_radix(kvm)) {
3228                 /* PS field - page size for VRMA */
3229                 dw0 = ((kvm->arch.vrma_slb_v & SLB_VSID_L) >> 1) |
3230                         ((kvm->arch.vrma_slb_v & SLB_VSID_LP) << 1);
3231                 /* HTABSIZE and HTABORG fields */
3232                 dw0 |= kvm->arch.sdr1;
3233
3234                 /* Second dword as set by userspace */
3235                 dw1 = kvm->arch.process_table;
3236         } else {
3237                 dw0 = PATB_HR | radix__get_tree_size() |
3238                         __pa(kvm->arch.pgtable) | RADIX_PGD_INDEX_SIZE;
3239                 dw1 = PATB_GR | kvm->arch.process_table;
3240         }
3241
3242         mmu_partition_table_set_entry(kvm->arch.lpid, dw0, dw1);
3243 }
3244
3245 static int kvmppc_hv_setup_htab_rma(struct kvm_vcpu *vcpu)
3246 {
3247         int err = 0;
3248         struct kvm *kvm = vcpu->kvm;
3249         unsigned long hva;
3250         struct kvm_memory_slot *memslot;
3251         struct vm_area_struct *vma;
3252         unsigned long lpcr = 0, senc;
3253         unsigned long psize, porder;
3254         int srcu_idx;
3255
3256         mutex_lock(&kvm->lock);
3257         if (kvm->arch.hpte_setup_done)
3258                 goto out;       /* another vcpu beat us to it */
3259
3260         /* Allocate hashed page table (if not done already) and reset it */
3261         if (!kvm->arch.hpt.virt) {
3262                 int order = KVM_DEFAULT_HPT_ORDER;
3263                 struct kvm_hpt_info info;
3264
3265                 err = kvmppc_allocate_hpt(&info, order);
3266                 /* If we get here, it means userspace didn't specify a
3267                  * size explicitly.  So, try successively smaller
3268                  * sizes if the default failed. */
3269                 while ((err == -ENOMEM) && --order >= PPC_MIN_HPT_ORDER)
3270                         err  = kvmppc_allocate_hpt(&info, order);
3271
3272                 if (err < 0) {
3273                         pr_err("KVM: Couldn't alloc HPT\n");
3274                         goto out;
3275                 }
3276
3277                 kvmppc_set_hpt(kvm, &info);
3278         }
3279
3280         /* Look up the memslot for guest physical address 0 */
3281         srcu_idx = srcu_read_lock(&kvm->srcu);
3282         memslot = gfn_to_memslot(kvm, 0);
3283
3284         /* We must have some memory at 0 by now */
3285         err = -EINVAL;
3286         if (!memslot || (memslot->flags & KVM_MEMSLOT_INVALID))
3287                 goto out_srcu;
3288
3289         /* Look up the VMA for the start of this memory slot */
3290         hva = memslot->userspace_addr;
3291         down_read(&current->mm->mmap_sem);
3292         vma = find_vma(current->mm, hva);
3293         if (!vma || vma->vm_start > hva || (vma->vm_flags & VM_IO))
3294                 goto up_out;
3295
3296         psize = vma_kernel_pagesize(vma);
3297         porder = __ilog2(psize);
3298
3299         up_read(&current->mm->mmap_sem);
3300
3301         /* We can handle 4k, 64k or 16M pages in the VRMA */
3302         err = -EINVAL;
3303         if (!(psize == 0x1000 || psize == 0x10000 ||
3304               psize == 0x1000000))
3305                 goto out_srcu;
3306
3307         senc = slb_pgsize_encoding(psize);
3308         kvm->arch.vrma_slb_v = senc | SLB_VSID_B_1T |
3309                 (VRMA_VSID << SLB_VSID_SHIFT_1T);
3310         /* Create HPTEs in the hash page table for the VRMA */
3311         kvmppc_map_vrma(vcpu, memslot, porder);
3312
3313         /* Update VRMASD field in the LPCR */
3314         if (!cpu_has_feature(CPU_FTR_ARCH_300)) {
3315                 /* the -4 is to account for senc values starting at 0x10 */
3316                 lpcr = senc << (LPCR_VRMASD_SH - 4);
3317                 kvmppc_update_lpcr(kvm, lpcr, LPCR_VRMASD);
3318         } else {
3319                 kvmppc_setup_partition_table(kvm);
3320         }
3321
3322         /* Order updates to kvm->arch.lpcr etc. vs. hpte_setup_done */
3323         smp_wmb();
3324         kvm->arch.hpte_setup_done = 1;
3325         err = 0;
3326  out_srcu:
3327         srcu_read_unlock(&kvm->srcu, srcu_idx);
3328  out:
3329         mutex_unlock(&kvm->lock);
3330         return err;
3331
3332  up_out:
3333         up_read(&current->mm->mmap_sem);
3334         goto out_srcu;
3335 }
3336
3337 #ifdef CONFIG_KVM_XICS
3338 /*
3339  * Allocate a per-core structure for managing state about which cores are
3340  * running in the host versus the guest and for exchanging data between
3341  * real mode KVM and CPU running in the host.
3342  * This is only done for the first VM.
3343  * The allocated structure stays even if all VMs have stopped.
3344  * It is only freed when the kvm-hv module is unloaded.
3345  * It's OK for this routine to fail, we just don't support host
3346  * core operations like redirecting H_IPI wakeups.
3347  */
3348 void kvmppc_alloc_host_rm_ops(void)
3349 {
3350         struct kvmppc_host_rm_ops *ops;
3351         unsigned long l_ops;
3352         int cpu, core;
3353         int size;
3354
3355         /* Not the first time here ? */
3356         if (kvmppc_host_rm_ops_hv != NULL)
3357                 return;
3358
3359         ops = kzalloc(sizeof(struct kvmppc_host_rm_ops), GFP_KERNEL);
3360         if (!ops)
3361                 return;
3362
3363         size = cpu_nr_cores() * sizeof(struct kvmppc_host_rm_core);
3364         ops->rm_core = kzalloc(size, GFP_KERNEL);
3365
3366         if (!ops->rm_core) {
3367                 kfree(ops);
3368                 return;
3369         }
3370
3371         get_online_cpus();
3372
3373         for (cpu = 0; cpu < nr_cpu_ids; cpu += threads_per_core) {
3374                 if (!cpu_online(cpu))
3375                         continue;
3376
3377                 core = cpu >> threads_shift;
3378                 ops->rm_core[core].rm_state.in_host = 1;
3379         }
3380
3381         ops->vcpu_kick = kvmppc_fast_vcpu_kick_hv;
3382
3383         /*
3384          * Make the contents of the kvmppc_host_rm_ops structure visible
3385          * to other CPUs before we assign it to the global variable.
3386          * Do an atomic assignment (no locks used here), but if someone
3387          * beats us to it, just free our copy and return.
3388          */
3389         smp_wmb();
3390         l_ops = (unsigned long) ops;
3391
3392         if (cmpxchg64((unsigned long *)&kvmppc_host_rm_ops_hv, 0, l_ops)) {
3393                 put_online_cpus();
3394                 kfree(ops->rm_core);
3395                 kfree(ops);
3396                 return;
3397         }
3398
3399         cpuhp_setup_state_nocalls(CPUHP_KVM_PPC_BOOK3S_PREPARE,
3400                                   "ppc/kvm_book3s:prepare",
3401                                   kvmppc_set_host_core,
3402                                   kvmppc_clear_host_core);
3403         put_online_cpus();
3404 }
3405
3406 void kvmppc_free_host_rm_ops(void)
3407 {
3408         if (kvmppc_host_rm_ops_hv) {
3409                 cpuhp_remove_state_nocalls(CPUHP_KVM_PPC_BOOK3S_PREPARE);
3410                 kfree(kvmppc_host_rm_ops_hv->rm_core);
3411                 kfree(kvmppc_host_rm_ops_hv);
3412                 kvmppc_host_rm_ops_hv = NULL;
3413         }
3414 }
3415 #endif
3416
3417 static int kvmppc_core_init_vm_hv(struct kvm *kvm)
3418 {
3419         unsigned long lpcr, lpid;
3420         char buf[32];
3421         int ret;
3422
3423         /* Allocate the guest's logical partition ID */
3424
3425         lpid = kvmppc_alloc_lpid();
3426         if ((long)lpid < 0)
3427                 return -ENOMEM;
3428         kvm->arch.lpid = lpid;
3429
3430         kvmppc_alloc_host_rm_ops();
3431
3432         /*
3433          * Since we don't flush the TLB when tearing down a VM,
3434          * and this lpid might have previously been used,
3435          * make sure we flush on each core before running the new VM.
3436          * On POWER9, the tlbie in mmu_partition_table_set_entry()
3437          * does this flush for us.
3438          */
3439         if (!cpu_has_feature(CPU_FTR_ARCH_300))
3440                 cpumask_setall(&kvm->arch.need_tlb_flush);
3441
3442         /* Start out with the default set of hcalls enabled */
3443         memcpy(kvm->arch.enabled_hcalls, default_enabled_hcalls,
3444                sizeof(kvm->arch.enabled_hcalls));
3445
3446         if (!cpu_has_feature(CPU_FTR_ARCH_300))
3447                 kvm->arch.host_sdr1 = mfspr(SPRN_SDR1);
3448
3449         /* Init LPCR for virtual RMA mode */
3450         kvm->arch.host_lpid = mfspr(SPRN_LPID);
3451         kvm->arch.host_lpcr = lpcr = mfspr(SPRN_LPCR);
3452         lpcr &= LPCR_PECE | LPCR_LPES;
3453         lpcr |= (4UL << LPCR_DPFD_SH) | LPCR_HDICE |
3454                 LPCR_VPM0 | LPCR_VPM1;
3455         kvm->arch.vrma_slb_v = SLB_VSID_B_1T |
3456                 (VRMA_VSID << SLB_VSID_SHIFT_1T);
3457         /* On POWER8 turn on online bit to enable PURR/SPURR */
3458         if (cpu_has_feature(CPU_FTR_ARCH_207S))
3459                 lpcr |= LPCR_ONL;
3460         /*
3461          * On POWER9, VPM0 bit is reserved (VPM0=1 behaviour is assumed)
3462          * Set HVICE bit to enable hypervisor virtualization interrupts.
3463          * Set HEIC to prevent OS interrupts to go to hypervisor (should
3464          * be unnecessary but better safe than sorry in case we re-enable
3465          * EE in HV mode with this LPCR still set)
3466          */
3467         if (cpu_has_feature(CPU_FTR_ARCH_300)) {
3468                 lpcr &= ~LPCR_VPM0;
3469                 lpcr |= LPCR_HVICE | LPCR_HEIC;
3470
3471                 /*
3472                  * If xive is enabled, we route 0x500 interrupts directly
3473                  * to the guest.
3474                  */
3475                 if (xive_enabled())
3476                         lpcr |= LPCR_LPES;
3477         }
3478
3479         /*
3480          * For now, if the host uses radix, the guest must be radix.
3481          */
3482         if (radix_enabled()) {
3483                 kvm->arch.radix = 1;
3484                 lpcr &= ~LPCR_VPM1;
3485                 lpcr |= LPCR_UPRT | LPCR_GTSE | LPCR_HR;
3486                 ret = kvmppc_init_vm_radix(kvm);
3487                 if (ret) {
3488                         kvmppc_free_lpid(kvm->arch.lpid);
3489                         return ret;
3490                 }
3491                 kvmppc_setup_partition_table(kvm);
3492         }
3493
3494         kvm->arch.lpcr = lpcr;
3495
3496         /* Initialization for future HPT resizes */
3497         kvm->arch.resize_hpt = NULL;
3498
3499         /*
3500          * Work out how many sets the TLB has, for the use of
3501          * the TLB invalidation loop in book3s_hv_rmhandlers.S.
3502          */
3503         if (kvm_is_radix(kvm))
3504                 kvm->arch.tlb_sets = POWER9_TLB_SETS_RADIX;     /* 128 */
3505         else if (cpu_has_feature(CPU_FTR_ARCH_300))
3506                 kvm->arch.tlb_sets = POWER9_TLB_SETS_HASH;      /* 256 */
3507         else if (cpu_has_feature(CPU_FTR_ARCH_207S))
3508                 kvm->arch.tlb_sets = POWER8_TLB_SETS;           /* 512 */
3509         else
3510                 kvm->arch.tlb_sets = POWER7_TLB_SETS;           /* 128 */
3511
3512         /*
3513          * Track that we now have a HV mode VM active. This blocks secondary
3514          * CPU threads from coming online.
3515          * On POWER9, we only need to do this for HPT guests on a radix
3516          * host, which is not yet supported.
3517          */
3518         if (!cpu_has_feature(CPU_FTR_ARCH_300))
3519                 kvm_hv_vm_activated();
3520
3521         /*
3522          * Create a debugfs directory for the VM
3523          */
3524         snprintf(buf, sizeof(buf), "vm%d", current->pid);
3525         kvm->arch.debugfs_dir = debugfs_create_dir(buf, kvm_debugfs_dir);
3526         if (!IS_ERR_OR_NULL(kvm->arch.debugfs_dir))
3527                 kvmppc_mmu_debugfs_init(kvm);
3528
3529         return 0;
3530 }
3531
3532 static void kvmppc_free_vcores(struct kvm *kvm)
3533 {
3534         long int i;
3535
3536         for (i = 0; i < KVM_MAX_VCORES; ++i)
3537                 kfree(kvm->arch.vcores[i]);
3538         kvm->arch.online_vcores = 0;
3539 }
3540
3541 static void kvmppc_core_destroy_vm_hv(struct kvm *kvm)
3542 {
3543         debugfs_remove_recursive(kvm->arch.debugfs_dir);
3544
3545         if (!cpu_has_feature(CPU_FTR_ARCH_300))
3546                 kvm_hv_vm_deactivated();
3547
3548         kvmppc_free_vcores(kvm);
3549
3550         kvmppc_free_lpid(kvm->arch.lpid);
3551
3552         if (kvm_is_radix(kvm))
3553                 kvmppc_free_radix(kvm);
3554         else
3555                 kvmppc_free_hpt(&kvm->arch.hpt);
3556
3557         kvmppc_free_pimap(kvm);
3558 }
3559
3560 /* We don't need to emulate any privileged instructions or dcbz */
3561 static int kvmppc_core_emulate_op_hv(struct kvm_run *run, struct kvm_vcpu *vcpu,
3562                                      unsigned int inst, int *advance)
3563 {
3564         return EMULATE_FAIL;
3565 }
3566
3567 static int kvmppc_core_emulate_mtspr_hv(struct kvm_vcpu *vcpu, int sprn,
3568                                         ulong spr_val)
3569 {
3570         return EMULATE_FAIL;
3571 }
3572
3573 static int kvmppc_core_emulate_mfspr_hv(struct kvm_vcpu *vcpu, int sprn,
3574                                         ulong *spr_val)
3575 {
3576         return EMULATE_FAIL;
3577 }
3578
3579 static int kvmppc_core_check_processor_compat_hv(void)
3580 {
3581         if (!cpu_has_feature(CPU_FTR_HVMODE) ||
3582             !cpu_has_feature(CPU_FTR_ARCH_206))
3583                 return -EIO;
3584
3585         return 0;
3586 }
3587
3588 #ifdef CONFIG_KVM_XICS
3589
3590 void kvmppc_free_pimap(struct kvm *kvm)
3591 {
3592         kfree(kvm->arch.pimap);
3593 }
3594
3595 static struct kvmppc_passthru_irqmap *kvmppc_alloc_pimap(void)
3596 {
3597         return kzalloc(sizeof(struct kvmppc_passthru_irqmap), GFP_KERNEL);
3598 }
3599
3600 static int kvmppc_set_passthru_irq(struct kvm *kvm, int host_irq, int guest_gsi)
3601 {
3602         struct irq_desc *desc;
3603         struct kvmppc_irq_map *irq_map;
3604         struct kvmppc_passthru_irqmap *pimap;
3605         struct irq_chip *chip;
3606         int i, rc = 0;
3607
3608         if (!kvm_irq_bypass)
3609                 return 1;
3610
3611         desc = irq_to_desc(host_irq);
3612         if (!desc)
3613                 return -EIO;
3614
3615         mutex_lock(&kvm->lock);
3616
3617         pimap = kvm->arch.pimap;
3618         if (pimap == NULL) {
3619                 /* First call, allocate structure to hold IRQ map */
3620                 pimap = kvmppc_alloc_pimap();
3621                 if (pimap == NULL) {
3622                         mutex_unlock(&kvm->lock);
3623                         return -ENOMEM;
3624                 }
3625                 kvm->arch.pimap = pimap;
3626         }
3627
3628         /*
3629          * For now, we only support interrupts for which the EOI operation
3630          * is an OPAL call followed by a write to XIRR, since that's
3631          * what our real-mode EOI code does, or a XIVE interrupt
3632          */
3633         chip = irq_data_get_irq_chip(&desc->irq_data);
3634         if (!chip || !(is_pnv_opal_msi(chip) || is_xive_irq(chip))) {
3635                 pr_warn("kvmppc_set_passthru_irq_hv: Could not assign IRQ map for (%d,%d)\n",
3636                         host_irq, guest_gsi);
3637                 mutex_unlock(&kvm->lock);
3638                 return -ENOENT;
3639         }
3640
3641         /*
3642          * See if we already have an entry for this guest IRQ number.
3643          * If it's mapped to a hardware IRQ number, that's an error,
3644          * otherwise re-use this entry.
3645          */
3646         for (i = 0; i < pimap->n_mapped; i++) {
3647                 if (guest_gsi == pimap->mapped[i].v_hwirq) {
3648                         if (pimap->mapped[i].r_hwirq) {
3649                                 mutex_unlock(&kvm->lock);
3650                                 return -EINVAL;
3651                         }
3652                         break;
3653                 }
3654         }
3655
3656         if (i == KVMPPC_PIRQ_MAPPED) {
3657                 mutex_unlock(&kvm->lock);
3658                 return -EAGAIN;         /* table is full */
3659         }
3660
3661         irq_map = &pimap->mapped[i];
3662
3663         irq_map->v_hwirq = guest_gsi;
3664         irq_map->desc = desc;
3665
3666         /*
3667          * Order the above two stores before the next to serialize with
3668          * the KVM real mode handler.
3669          */
3670         smp_wmb();
3671         irq_map->r_hwirq = desc->irq_data.hwirq;
3672
3673         if (i == pimap->n_mapped)
3674                 pimap->n_mapped++;
3675
3676         if (xive_enabled())
3677                 rc = kvmppc_xive_set_mapped(kvm, guest_gsi, desc);
3678         else
3679                 kvmppc_xics_set_mapped(kvm, guest_gsi, desc->irq_data.hwirq);
3680         if (rc)
3681                 irq_map->r_hwirq = 0;
3682
3683         mutex_unlock(&kvm->lock);
3684
3685         return 0;
3686 }
3687
3688 static int kvmppc_clr_passthru_irq(struct kvm *kvm, int host_irq, int guest_gsi)
3689 {
3690         struct irq_desc *desc;
3691         struct kvmppc_passthru_irqmap *pimap;
3692         int i, rc = 0;
3693
3694         if (!kvm_irq_bypass)
3695                 return 0;
3696
3697         desc = irq_to_desc(host_irq);
3698         if (!desc)
3699                 return -EIO;
3700
3701         mutex_lock(&kvm->lock);
3702         if (!kvm->arch.pimap)
3703                 goto unlock;
3704
3705         pimap = kvm->arch.pimap;
3706
3707         for (i = 0; i < pimap->n_mapped; i++) {
3708                 if (guest_gsi == pimap->mapped[i].v_hwirq)
3709                         break;
3710         }
3711
3712         if (i == pimap->n_mapped) {
3713                 mutex_unlock(&kvm->lock);
3714                 return -ENODEV;
3715         }
3716
3717         if (xive_enabled())
3718                 rc = kvmppc_xive_clr_mapped(kvm, guest_gsi, pimap->mapped[i].desc);
3719         else
3720                 kvmppc_xics_clr_mapped(kvm, guest_gsi, pimap->mapped[i].r_hwirq);
3721
3722         /* invalidate the entry (what do do on error from the above ?) */
3723         pimap->mapped[i].r_hwirq = 0;
3724
3725         /*
3726          * We don't free this structure even when the count goes to
3727          * zero. The structure is freed when we destroy the VM.
3728          */
3729  unlock:
3730         mutex_unlock(&kvm->lock);
3731         return rc;
3732 }
3733
3734 static int kvmppc_irq_bypass_add_producer_hv(struct irq_bypass_consumer *cons,
3735                                              struct irq_bypass_producer *prod)
3736 {
3737         int ret = 0;
3738         struct kvm_kernel_irqfd *irqfd =
3739                 container_of(cons, struct kvm_kernel_irqfd, consumer);
3740
3741         irqfd->producer = prod;
3742
3743         ret = kvmppc_set_passthru_irq(irqfd->kvm, prod->irq, irqfd->gsi);
3744         if (ret)
3745                 pr_info("kvmppc_set_passthru_irq (irq %d, gsi %d) fails: %d\n",
3746                         prod->irq, irqfd->gsi, ret);
3747
3748         return ret;
3749 }
3750
3751 static void kvmppc_irq_bypass_del_producer_hv(struct irq_bypass_consumer *cons,
3752                                               struct irq_bypass_producer *prod)
3753 {
3754         int ret;
3755         struct kvm_kernel_irqfd *irqfd =
3756                 container_of(cons, struct kvm_kernel_irqfd, consumer);
3757
3758         irqfd->producer = NULL;
3759
3760         /*
3761          * When producer of consumer is unregistered, we change back to
3762          * default external interrupt handling mode - KVM real mode
3763          * will switch back to host.
3764          */
3765         ret = kvmppc_clr_passthru_irq(irqfd->kvm, prod->irq, irqfd->gsi);
3766         if (ret)
3767                 pr_warn("kvmppc_clr_passthru_irq (irq %d, gsi %d) fails: %d\n",
3768                         prod->irq, irqfd->gsi, ret);
3769 }
3770 #endif
3771
3772 static long kvm_arch_vm_ioctl_hv(struct file *filp,
3773                                  unsigned int ioctl, unsigned long arg)
3774 {
3775         struct kvm *kvm __maybe_unused = filp->private_data;
3776         void __user *argp = (void __user *)arg;
3777         long r;
3778
3779         switch (ioctl) {
3780
3781         case KVM_PPC_ALLOCATE_HTAB: {
3782                 u32 htab_order;
3783
3784                 r = -EFAULT;
3785                 if (get_user(htab_order, (u32 __user *)argp))
3786                         break;
3787                 r = kvmppc_alloc_reset_hpt(kvm, htab_order);
3788                 if (r)
3789                         break;
3790                 r = 0;
3791                 break;
3792         }
3793
3794         case KVM_PPC_GET_HTAB_FD: {
3795                 struct kvm_get_htab_fd ghf;
3796
3797                 r = -EFAULT;
3798                 if (copy_from_user(&ghf, argp, sizeof(ghf)))
3799                         break;
3800                 r = kvm_vm_ioctl_get_htab_fd(kvm, &ghf);
3801                 break;
3802         }
3803
3804         case KVM_PPC_RESIZE_HPT_PREPARE: {
3805                 struct kvm_ppc_resize_hpt rhpt;
3806
3807                 r = -EFAULT;
3808                 if (copy_from_user(&rhpt, argp, sizeof(rhpt)))
3809                         break;
3810
3811                 r = kvm_vm_ioctl_resize_hpt_prepare(kvm, &rhpt);
3812                 break;
3813         }
3814
3815         case KVM_PPC_RESIZE_HPT_COMMIT: {
3816                 struct kvm_ppc_resize_hpt rhpt;
3817
3818                 r = -EFAULT;
3819                 if (copy_from_user(&rhpt, argp, sizeof(rhpt)))
3820                         break;
3821
3822                 r = kvm_vm_ioctl_resize_hpt_commit(kvm, &rhpt);
3823                 break;
3824         }
3825
3826         default:
3827                 r = -ENOTTY;
3828         }
3829
3830         return r;
3831 }
3832
3833 /*
3834  * List of hcall numbers to enable by default.
3835  * For compatibility with old userspace, we enable by default
3836  * all hcalls that were implemented before the hcall-enabling
3837  * facility was added.  Note this list should not include H_RTAS.
3838  */
3839 static unsigned int default_hcall_list[] = {
3840         H_REMOVE,
3841         H_ENTER,
3842         H_READ,
3843         H_PROTECT,
3844         H_BULK_REMOVE,
3845         H_GET_TCE,
3846         H_PUT_TCE,
3847         H_SET_DABR,
3848         H_SET_XDABR,
3849         H_CEDE,
3850         H_PROD,
3851         H_CONFER,
3852         H_REGISTER_VPA,
3853 #ifdef CONFIG_KVM_XICS
3854         H_EOI,
3855         H_CPPR,
3856         H_IPI,
3857         H_IPOLL,
3858         H_XIRR,
3859         H_XIRR_X,
3860 #endif
3861         0
3862 };
3863
3864 static void init_default_hcalls(void)
3865 {
3866         int i;
3867         unsigned int hcall;
3868
3869         for (i = 0; default_hcall_list[i]; ++i) {
3870                 hcall = default_hcall_list[i];
3871                 WARN_ON(!kvmppc_hcall_impl_hv(hcall));
3872                 __set_bit(hcall / 4, default_enabled_hcalls);
3873         }
3874 }
3875
3876 static int kvmhv_configure_mmu(struct kvm *kvm, struct kvm_ppc_mmuv3_cfg *cfg)
3877 {
3878         unsigned long lpcr;
3879         int radix;
3880
3881         /* If not on a POWER9, reject it */
3882         if (!cpu_has_feature(CPU_FTR_ARCH_300))
3883                 return -ENODEV;
3884
3885         /* If any unknown flags set, reject it */
3886         if (cfg->flags & ~(KVM_PPC_MMUV3_RADIX | KVM_PPC_MMUV3_GTSE))
3887                 return -EINVAL;
3888
3889         /* We can't change a guest to/from radix yet */
3890         radix = !!(cfg->flags & KVM_PPC_MMUV3_RADIX);
3891         if (radix != kvm_is_radix(kvm))
3892                 return -EINVAL;
3893
3894         /* GR (guest radix) bit in process_table field must match */
3895         if (!!(cfg->process_table & PATB_GR) != radix)
3896                 return -EINVAL;
3897
3898         /* Process table size field must be reasonable, i.e. <= 24 */
3899         if ((cfg->process_table & PRTS_MASK) > 24)
3900                 return -EINVAL;
3901
3902         kvm->arch.process_table = cfg->process_table;
3903         kvmppc_setup_partition_table(kvm);
3904
3905         lpcr = (cfg->flags & KVM_PPC_MMUV3_GTSE) ? LPCR_GTSE : 0;
3906         kvmppc_update_lpcr(kvm, lpcr, LPCR_GTSE);
3907
3908         return 0;
3909 }
3910
3911 static struct kvmppc_ops kvm_ops_hv = {
3912         .get_sregs = kvm_arch_vcpu_ioctl_get_sregs_hv,
3913         .set_sregs = kvm_arch_vcpu_ioctl_set_sregs_hv,
3914         .get_one_reg = kvmppc_get_one_reg_hv,
3915         .set_one_reg = kvmppc_set_one_reg_hv,
3916         .vcpu_load   = kvmppc_core_vcpu_load_hv,
3917         .vcpu_put    = kvmppc_core_vcpu_put_hv,
3918         .set_msr     = kvmppc_set_msr_hv,
3919         .vcpu_run    = kvmppc_vcpu_run_hv,
3920         .vcpu_create = kvmppc_core_vcpu_create_hv,
3921         .vcpu_free   = kvmppc_core_vcpu_free_hv,
3922         .check_requests = kvmppc_core_check_requests_hv,
3923         .get_dirty_log  = kvm_vm_ioctl_get_dirty_log_hv,
3924         .flush_memslot  = kvmppc_core_flush_memslot_hv,
3925         .prepare_memory_region = kvmppc_core_prepare_memory_region_hv,
3926         .commit_memory_region  = kvmppc_core_commit_memory_region_hv,
3927         .unmap_hva = kvm_unmap_hva_hv,
3928         .unmap_hva_range = kvm_unmap_hva_range_hv,
3929         .age_hva  = kvm_age_hva_hv,
3930         .test_age_hva = kvm_test_age_hva_hv,
3931         .set_spte_hva = kvm_set_spte_hva_hv,
3932         .mmu_destroy  = kvmppc_mmu_destroy_hv,
3933         .free_memslot = kvmppc_core_free_memslot_hv,
3934         .create_memslot = kvmppc_core_create_memslot_hv,
3935         .init_vm =  kvmppc_core_init_vm_hv,
3936         .destroy_vm = kvmppc_core_destroy_vm_hv,
3937         .get_smmu_info = kvm_vm_ioctl_get_smmu_info_hv,
3938         .emulate_op = kvmppc_core_emulate_op_hv,
3939         .emulate_mtspr = kvmppc_core_emulate_mtspr_hv,
3940         .emulate_mfspr = kvmppc_core_emulate_mfspr_hv,
3941         .fast_vcpu_kick = kvmppc_fast_vcpu_kick_hv,
3942         .arch_vm_ioctl  = kvm_arch_vm_ioctl_hv,
3943         .hcall_implemented = kvmppc_hcall_impl_hv,
3944 #ifdef CONFIG_KVM_XICS
3945         .irq_bypass_add_producer = kvmppc_irq_bypass_add_producer_hv,
3946         .irq_bypass_del_producer = kvmppc_irq_bypass_del_producer_hv,
3947 #endif
3948         .configure_mmu = kvmhv_configure_mmu,
3949         .get_rmmu_info = kvmhv_get_rmmu_info,
3950 };
3951
3952 static int kvm_init_subcore_bitmap(void)
3953 {
3954         int i, j;
3955         int nr_cores = cpu_nr_cores();
3956         struct sibling_subcore_state *sibling_subcore_state;
3957
3958         for (i = 0; i < nr_cores; i++) {
3959                 int first_cpu = i * threads_per_core;
3960                 int node = cpu_to_node(first_cpu);
3961
3962                 /* Ignore if it is already allocated. */
3963                 if (paca[first_cpu].sibling_subcore_state)
3964                         continue;
3965
3966                 sibling_subcore_state =
3967                         kmalloc_node(sizeof(struct sibling_subcore_state),
3968                                                         GFP_KERNEL, node);
3969                 if (!sibling_subcore_state)
3970                         return -ENOMEM;
3971
3972                 memset(sibling_subcore_state, 0,
3973                                 sizeof(struct sibling_subcore_state));
3974
3975                 for (j = 0; j < threads_per_core; j++) {
3976                         int cpu = first_cpu + j;
3977
3978                         paca[cpu].sibling_subcore_state = sibling_subcore_state;
3979                 }
3980         }
3981         return 0;
3982 }
3983
3984 static int kvmppc_radix_possible(void)
3985 {
3986         return cpu_has_feature(CPU_FTR_ARCH_300) && radix_enabled();
3987 }
3988
3989 static int kvmppc_book3s_init_hv(void)
3990 {
3991         int r;
3992         /*
3993          * FIXME!! Do we need to check on all cpus ?
3994          */
3995         r = kvmppc_core_check_processor_compat_hv();
3996         if (r < 0)
3997                 return -ENODEV;
3998
3999         r = kvm_init_subcore_bitmap();
4000         if (r)
4001                 return r;
4002
4003         /*
4004          * We need a way of accessing the XICS interrupt controller,
4005          * either directly, via paca[cpu].kvm_hstate.xics_phys, or
4006          * indirectly, via OPAL.
4007          */
4008 #ifdef CONFIG_SMP
4009         if (!xive_enabled() && !local_paca->kvm_hstate.xics_phys) {
4010                 struct device_node *np;
4011
4012                 np = of_find_compatible_node(NULL, NULL, "ibm,opal-intc");
4013                 if (!np) {
4014                         pr_err("KVM-HV: Cannot determine method for accessing XICS\n");
4015                         return -ENODEV;
4016                 }
4017         }
4018 #endif
4019
4020         kvm_ops_hv.owner = THIS_MODULE;
4021         kvmppc_hv_ops = &kvm_ops_hv;
4022
4023         init_default_hcalls();
4024
4025         init_vcore_lists();
4026
4027         r = kvmppc_mmu_hv_init();
4028         if (r)
4029                 return r;
4030
4031         if (kvmppc_radix_possible())
4032                 r = kvmppc_radix_init();
4033         return r;
4034 }
4035
4036 static void kvmppc_book3s_exit_hv(void)
4037 {
4038         kvmppc_free_host_rm_ops();
4039         if (kvmppc_radix_possible())
4040                 kvmppc_radix_exit();
4041         kvmppc_hv_ops = NULL;
4042 }
4043
4044 module_init(kvmppc_book3s_init_hv);
4045 module_exit(kvmppc_book3s_exit_hv);
4046 MODULE_LICENSE("GPL");
4047 MODULE_ALIAS_MISCDEV(KVM_MINOR);
4048 MODULE_ALIAS("devname:kvm");
4049