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