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