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