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