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