]> git.kernelconcepts.de Git - karo-tx-linux.git/blob - arch/powerpc/kvm/book3s_hv.c
kvm: powerpc: book3s: Add is_hv_enabled to kvmppc_ops
[karo-tx-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/cpumask.h>
31 #include <linux/spinlock.h>
32 #include <linux/page-flags.h>
33 #include <linux/srcu.h>
34
35 #include <asm/reg.h>
36 #include <asm/cputable.h>
37 #include <asm/cacheflush.h>
38 #include <asm/tlbflush.h>
39 #include <asm/uaccess.h>
40 #include <asm/io.h>
41 #include <asm/kvm_ppc.h>
42 #include <asm/kvm_book3s.h>
43 #include <asm/mmu_context.h>
44 #include <asm/lppaca.h>
45 #include <asm/processor.h>
46 #include <asm/cputhreads.h>
47 #include <asm/page.h>
48 #include <asm/hvcall.h>
49 #include <asm/switch_to.h>
50 #include <asm/smp.h>
51 #include <linux/gfp.h>
52 #include <linux/vmalloc.h>
53 #include <linux/highmem.h>
54 #include <linux/hugetlb.h>
55
56 #include "book3s.h"
57
58 /* #define EXIT_DEBUG */
59 /* #define EXIT_DEBUG_SIMPLE */
60 /* #define EXIT_DEBUG_INT */
61
62 /* Used to indicate that a guest page fault needs to be handled */
63 #define RESUME_PAGE_FAULT       (RESUME_GUEST | RESUME_FLAG_ARCH1)
64
65 /* Used as a "null" value for timebase values */
66 #define TB_NIL  (~(u64)0)
67
68 static void kvmppc_end_cede(struct kvm_vcpu *vcpu);
69 static int kvmppc_hv_setup_htab_rma(struct kvm_vcpu *vcpu);
70
71 static void kvmppc_fast_vcpu_kick_hv(struct kvm_vcpu *vcpu)
72 {
73         int me;
74         int cpu = vcpu->cpu;
75         wait_queue_head_t *wqp;
76
77         wqp = kvm_arch_vcpu_wq(vcpu);
78         if (waitqueue_active(wqp)) {
79                 wake_up_interruptible(wqp);
80                 ++vcpu->stat.halt_wakeup;
81         }
82
83         me = get_cpu();
84
85         /* CPU points to the first thread of the core */
86         if (cpu != me && cpu >= 0 && cpu < nr_cpu_ids) {
87                 int real_cpu = cpu + vcpu->arch.ptid;
88                 if (paca[real_cpu].kvm_hstate.xics_phys)
89                         xics_wake_cpu(real_cpu);
90                 else if (cpu_online(cpu))
91                         smp_send_reschedule(cpu);
92         }
93         put_cpu();
94 }
95
96 /*
97  * We use the vcpu_load/put functions to measure stolen time.
98  * Stolen time is counted as time when either the vcpu is able to
99  * run as part of a virtual core, but the task running the vcore
100  * is preempted or sleeping, or when the vcpu needs something done
101  * in the kernel by the task running the vcpu, but that task is
102  * preempted or sleeping.  Those two things have to be counted
103  * separately, since one of the vcpu tasks will take on the job
104  * of running the core, and the other vcpu tasks in the vcore will
105  * sleep waiting for it to do that, but that sleep shouldn't count
106  * as stolen time.
107  *
108  * Hence we accumulate stolen time when the vcpu can run as part of
109  * a vcore using vc->stolen_tb, and the stolen time when the vcpu
110  * needs its task to do other things in the kernel (for example,
111  * service a page fault) in busy_stolen.  We don't accumulate
112  * stolen time for a vcore when it is inactive, or for a vcpu
113  * when it is in state RUNNING or NOTREADY.  NOTREADY is a bit of
114  * a misnomer; it means that the vcpu task is not executing in
115  * the KVM_VCPU_RUN ioctl, i.e. it is in userspace or elsewhere in
116  * the kernel.  We don't have any way of dividing up that time
117  * between time that the vcpu is genuinely stopped, time that
118  * the task is actively working on behalf of the vcpu, and time
119  * that the task is preempted, so we don't count any of it as
120  * stolen.
121  *
122  * Updates to busy_stolen are protected by arch.tbacct_lock;
123  * updates to vc->stolen_tb are protected by the arch.tbacct_lock
124  * of the vcpu that has taken responsibility for running the vcore
125  * (i.e. vc->runner).  The stolen times are measured in units of
126  * timebase ticks.  (Note that the != TB_NIL checks below are
127  * purely defensive; they should never fail.)
128  */
129
130 static void kvmppc_core_vcpu_load_hv(struct kvm_vcpu *vcpu, int cpu)
131 {
132         struct kvmppc_vcore *vc = vcpu->arch.vcore;
133
134         spin_lock(&vcpu->arch.tbacct_lock);
135         if (vc->runner == vcpu && vc->vcore_state != VCORE_INACTIVE &&
136             vc->preempt_tb != TB_NIL) {
137                 vc->stolen_tb += mftb() - vc->preempt_tb;
138                 vc->preempt_tb = TB_NIL;
139         }
140         if (vcpu->arch.state == KVMPPC_VCPU_BUSY_IN_HOST &&
141             vcpu->arch.busy_preempt != TB_NIL) {
142                 vcpu->arch.busy_stolen += mftb() - vcpu->arch.busy_preempt;
143                 vcpu->arch.busy_preempt = TB_NIL;
144         }
145         spin_unlock(&vcpu->arch.tbacct_lock);
146 }
147
148 static void kvmppc_core_vcpu_put_hv(struct kvm_vcpu *vcpu)
149 {
150         struct kvmppc_vcore *vc = vcpu->arch.vcore;
151
152         spin_lock(&vcpu->arch.tbacct_lock);
153         if (vc->runner == vcpu && vc->vcore_state != VCORE_INACTIVE)
154                 vc->preempt_tb = mftb();
155         if (vcpu->arch.state == KVMPPC_VCPU_BUSY_IN_HOST)
156                 vcpu->arch.busy_preempt = mftb();
157         spin_unlock(&vcpu->arch.tbacct_lock);
158 }
159
160 static void kvmppc_set_msr_hv(struct kvm_vcpu *vcpu, u64 msr)
161 {
162         vcpu->arch.shregs.msr = msr;
163         kvmppc_end_cede(vcpu);
164 }
165
166 void kvmppc_set_pvr_hv(struct kvm_vcpu *vcpu, u32 pvr)
167 {
168         vcpu->arch.pvr = pvr;
169 }
170
171 int kvmppc_set_arch_compat(struct kvm_vcpu *vcpu, u32 arch_compat)
172 {
173         unsigned long pcr = 0;
174         struct kvmppc_vcore *vc = vcpu->arch.vcore;
175
176         if (arch_compat) {
177                 if (!cpu_has_feature(CPU_FTR_ARCH_206))
178                         return -EINVAL; /* 970 has no compat mode support */
179
180                 switch (arch_compat) {
181                 case PVR_ARCH_205:
182                         pcr = PCR_ARCH_205;
183                         break;
184                 case PVR_ARCH_206:
185                 case PVR_ARCH_206p:
186                         break;
187                 default:
188                         return -EINVAL;
189                 }
190         }
191
192         spin_lock(&vc->lock);
193         vc->arch_compat = arch_compat;
194         vc->pcr = pcr;
195         spin_unlock(&vc->lock);
196
197         return 0;
198 }
199
200 void kvmppc_dump_regs(struct kvm_vcpu *vcpu)
201 {
202         int r;
203
204         pr_err("vcpu %p (%d):\n", vcpu, vcpu->vcpu_id);
205         pr_err("pc  = %.16lx  msr = %.16llx  trap = %x\n",
206                vcpu->arch.pc, vcpu->arch.shregs.msr, vcpu->arch.trap);
207         for (r = 0; r < 16; ++r)
208                 pr_err("r%2d = %.16lx  r%d = %.16lx\n",
209                        r, kvmppc_get_gpr(vcpu, r),
210                        r+16, kvmppc_get_gpr(vcpu, r+16));
211         pr_err("ctr = %.16lx  lr  = %.16lx\n",
212                vcpu->arch.ctr, vcpu->arch.lr);
213         pr_err("srr0 = %.16llx srr1 = %.16llx\n",
214                vcpu->arch.shregs.srr0, vcpu->arch.shregs.srr1);
215         pr_err("sprg0 = %.16llx sprg1 = %.16llx\n",
216                vcpu->arch.shregs.sprg0, vcpu->arch.shregs.sprg1);
217         pr_err("sprg2 = %.16llx sprg3 = %.16llx\n",
218                vcpu->arch.shregs.sprg2, vcpu->arch.shregs.sprg3);
219         pr_err("cr = %.8x  xer = %.16lx  dsisr = %.8x\n",
220                vcpu->arch.cr, vcpu->arch.xer, vcpu->arch.shregs.dsisr);
221         pr_err("dar = %.16llx\n", vcpu->arch.shregs.dar);
222         pr_err("fault dar = %.16lx dsisr = %.8x\n",
223                vcpu->arch.fault_dar, vcpu->arch.fault_dsisr);
224         pr_err("SLB (%d entries):\n", vcpu->arch.slb_max);
225         for (r = 0; r < vcpu->arch.slb_max; ++r)
226                 pr_err("  ESID = %.16llx VSID = %.16llx\n",
227                        vcpu->arch.slb[r].orige, vcpu->arch.slb[r].origv);
228         pr_err("lpcr = %.16lx sdr1 = %.16lx last_inst = %.8x\n",
229                vcpu->arch.vcore->lpcr, vcpu->kvm->arch.sdr1,
230                vcpu->arch.last_inst);
231 }
232
233 struct kvm_vcpu *kvmppc_find_vcpu(struct kvm *kvm, int id)
234 {
235         int r;
236         struct kvm_vcpu *v, *ret = NULL;
237
238         mutex_lock(&kvm->lock);
239         kvm_for_each_vcpu(r, v, kvm) {
240                 if (v->vcpu_id == id) {
241                         ret = v;
242                         break;
243                 }
244         }
245         mutex_unlock(&kvm->lock);
246         return ret;
247 }
248
249 static void init_vpa(struct kvm_vcpu *vcpu, struct lppaca *vpa)
250 {
251         vpa->__old_status |= LPPACA_OLD_SHARED_PROC;
252         vpa->yield_count = 1;
253 }
254
255 static int set_vpa(struct kvm_vcpu *vcpu, struct kvmppc_vpa *v,
256                    unsigned long addr, unsigned long len)
257 {
258         /* check address is cacheline aligned */
259         if (addr & (L1_CACHE_BYTES - 1))
260                 return -EINVAL;
261         spin_lock(&vcpu->arch.vpa_update_lock);
262         if (v->next_gpa != addr || v->len != len) {
263                 v->next_gpa = addr;
264                 v->len = addr ? len : 0;
265                 v->update_pending = 1;
266         }
267         spin_unlock(&vcpu->arch.vpa_update_lock);
268         return 0;
269 }
270
271 /* Length for a per-processor buffer is passed in at offset 4 in the buffer */
272 struct reg_vpa {
273         u32 dummy;
274         union {
275                 u16 hword;
276                 u32 word;
277         } length;
278 };
279
280 static int vpa_is_registered(struct kvmppc_vpa *vpap)
281 {
282         if (vpap->update_pending)
283                 return vpap->next_gpa != 0;
284         return vpap->pinned_addr != NULL;
285 }
286
287 static unsigned long do_h_register_vpa(struct kvm_vcpu *vcpu,
288                                        unsigned long flags,
289                                        unsigned long vcpuid, unsigned long vpa)
290 {
291         struct kvm *kvm = vcpu->kvm;
292         unsigned long len, nb;
293         void *va;
294         struct kvm_vcpu *tvcpu;
295         int err;
296         int subfunc;
297         struct kvmppc_vpa *vpap;
298
299         tvcpu = kvmppc_find_vcpu(kvm, vcpuid);
300         if (!tvcpu)
301                 return H_PARAMETER;
302
303         subfunc = (flags >> H_VPA_FUNC_SHIFT) & H_VPA_FUNC_MASK;
304         if (subfunc == H_VPA_REG_VPA || subfunc == H_VPA_REG_DTL ||
305             subfunc == H_VPA_REG_SLB) {
306                 /* Registering new area - address must be cache-line aligned */
307                 if ((vpa & (L1_CACHE_BYTES - 1)) || !vpa)
308                         return H_PARAMETER;
309
310                 /* convert logical addr to kernel addr and read length */
311                 va = kvmppc_pin_guest_page(kvm, vpa, &nb);
312                 if (va == NULL)
313                         return H_PARAMETER;
314                 if (subfunc == H_VPA_REG_VPA)
315                         len = ((struct reg_vpa *)va)->length.hword;
316                 else
317                         len = ((struct reg_vpa *)va)->length.word;
318                 kvmppc_unpin_guest_page(kvm, va, vpa, false);
319
320                 /* Check length */
321                 if (len > nb || len < sizeof(struct reg_vpa))
322                         return H_PARAMETER;
323         } else {
324                 vpa = 0;
325                 len = 0;
326         }
327
328         err = H_PARAMETER;
329         vpap = NULL;
330         spin_lock(&tvcpu->arch.vpa_update_lock);
331
332         switch (subfunc) {
333         case H_VPA_REG_VPA:             /* register VPA */
334                 if (len < sizeof(struct lppaca))
335                         break;
336                 vpap = &tvcpu->arch.vpa;
337                 err = 0;
338                 break;
339
340         case H_VPA_REG_DTL:             /* register DTL */
341                 if (len < sizeof(struct dtl_entry))
342                         break;
343                 len -= len % sizeof(struct dtl_entry);
344
345                 /* Check that they have previously registered a VPA */
346                 err = H_RESOURCE;
347                 if (!vpa_is_registered(&tvcpu->arch.vpa))
348                         break;
349
350                 vpap = &tvcpu->arch.dtl;
351                 err = 0;
352                 break;
353
354         case H_VPA_REG_SLB:             /* register SLB shadow buffer */
355                 /* Check that they have previously registered a VPA */
356                 err = H_RESOURCE;
357                 if (!vpa_is_registered(&tvcpu->arch.vpa))
358                         break;
359
360                 vpap = &tvcpu->arch.slb_shadow;
361                 err = 0;
362                 break;
363
364         case H_VPA_DEREG_VPA:           /* deregister VPA */
365                 /* Check they don't still have a DTL or SLB buf registered */
366                 err = H_RESOURCE;
367                 if (vpa_is_registered(&tvcpu->arch.dtl) ||
368                     vpa_is_registered(&tvcpu->arch.slb_shadow))
369                         break;
370
371                 vpap = &tvcpu->arch.vpa;
372                 err = 0;
373                 break;
374
375         case H_VPA_DEREG_DTL:           /* deregister DTL */
376                 vpap = &tvcpu->arch.dtl;
377                 err = 0;
378                 break;
379
380         case H_VPA_DEREG_SLB:           /* deregister SLB shadow buffer */
381                 vpap = &tvcpu->arch.slb_shadow;
382                 err = 0;
383                 break;
384         }
385
386         if (vpap) {
387                 vpap->next_gpa = vpa;
388                 vpap->len = len;
389                 vpap->update_pending = 1;
390         }
391
392         spin_unlock(&tvcpu->arch.vpa_update_lock);
393
394         return err;
395 }
396
397 static void kvmppc_update_vpa(struct kvm_vcpu *vcpu, struct kvmppc_vpa *vpap)
398 {
399         struct kvm *kvm = vcpu->kvm;
400         void *va;
401         unsigned long nb;
402         unsigned long gpa;
403
404         /*
405          * We need to pin the page pointed to by vpap->next_gpa,
406          * but we can't call kvmppc_pin_guest_page under the lock
407          * as it does get_user_pages() and down_read().  So we
408          * have to drop the lock, pin the page, then get the lock
409          * again and check that a new area didn't get registered
410          * in the meantime.
411          */
412         for (;;) {
413                 gpa = vpap->next_gpa;
414                 spin_unlock(&vcpu->arch.vpa_update_lock);
415                 va = NULL;
416                 nb = 0;
417                 if (gpa)
418                         va = kvmppc_pin_guest_page(kvm, gpa, &nb);
419                 spin_lock(&vcpu->arch.vpa_update_lock);
420                 if (gpa == vpap->next_gpa)
421                         break;
422                 /* sigh... unpin that one and try again */
423                 if (va)
424                         kvmppc_unpin_guest_page(kvm, va, gpa, false);
425         }
426
427         vpap->update_pending = 0;
428         if (va && nb < vpap->len) {
429                 /*
430                  * If it's now too short, it must be that userspace
431                  * has changed the mappings underlying guest memory,
432                  * so unregister the region.
433                  */
434                 kvmppc_unpin_guest_page(kvm, va, gpa, false);
435                 va = NULL;
436         }
437         if (vpap->pinned_addr)
438                 kvmppc_unpin_guest_page(kvm, vpap->pinned_addr, vpap->gpa,
439                                         vpap->dirty);
440         vpap->gpa = gpa;
441         vpap->pinned_addr = va;
442         vpap->dirty = false;
443         if (va)
444                 vpap->pinned_end = va + vpap->len;
445 }
446
447 static void kvmppc_update_vpas(struct kvm_vcpu *vcpu)
448 {
449         if (!(vcpu->arch.vpa.update_pending ||
450               vcpu->arch.slb_shadow.update_pending ||
451               vcpu->arch.dtl.update_pending))
452                 return;
453
454         spin_lock(&vcpu->arch.vpa_update_lock);
455         if (vcpu->arch.vpa.update_pending) {
456                 kvmppc_update_vpa(vcpu, &vcpu->arch.vpa);
457                 if (vcpu->arch.vpa.pinned_addr)
458                         init_vpa(vcpu, vcpu->arch.vpa.pinned_addr);
459         }
460         if (vcpu->arch.dtl.update_pending) {
461                 kvmppc_update_vpa(vcpu, &vcpu->arch.dtl);
462                 vcpu->arch.dtl_ptr = vcpu->arch.dtl.pinned_addr;
463                 vcpu->arch.dtl_index = 0;
464         }
465         if (vcpu->arch.slb_shadow.update_pending)
466                 kvmppc_update_vpa(vcpu, &vcpu->arch.slb_shadow);
467         spin_unlock(&vcpu->arch.vpa_update_lock);
468 }
469
470 /*
471  * Return the accumulated stolen time for the vcore up until `now'.
472  * The caller should hold the vcore lock.
473  */
474 static u64 vcore_stolen_time(struct kvmppc_vcore *vc, u64 now)
475 {
476         u64 p;
477
478         /*
479          * If we are the task running the vcore, then since we hold
480          * the vcore lock, we can't be preempted, so stolen_tb/preempt_tb
481          * can't be updated, so we don't need the tbacct_lock.
482          * If the vcore is inactive, it can't become active (since we
483          * hold the vcore lock), so the vcpu load/put functions won't
484          * update stolen_tb/preempt_tb, and we don't need tbacct_lock.
485          */
486         if (vc->vcore_state != VCORE_INACTIVE &&
487             vc->runner->arch.run_task != current) {
488                 spin_lock(&vc->runner->arch.tbacct_lock);
489                 p = vc->stolen_tb;
490                 if (vc->preempt_tb != TB_NIL)
491                         p += now - vc->preempt_tb;
492                 spin_unlock(&vc->runner->arch.tbacct_lock);
493         } else {
494                 p = vc->stolen_tb;
495         }
496         return p;
497 }
498
499 static void kvmppc_create_dtl_entry(struct kvm_vcpu *vcpu,
500                                     struct kvmppc_vcore *vc)
501 {
502         struct dtl_entry *dt;
503         struct lppaca *vpa;
504         unsigned long stolen;
505         unsigned long core_stolen;
506         u64 now;
507
508         dt = vcpu->arch.dtl_ptr;
509         vpa = vcpu->arch.vpa.pinned_addr;
510         now = mftb();
511         core_stolen = vcore_stolen_time(vc, now);
512         stolen = core_stolen - vcpu->arch.stolen_logged;
513         vcpu->arch.stolen_logged = core_stolen;
514         spin_lock(&vcpu->arch.tbacct_lock);
515         stolen += vcpu->arch.busy_stolen;
516         vcpu->arch.busy_stolen = 0;
517         spin_unlock(&vcpu->arch.tbacct_lock);
518         if (!dt || !vpa)
519                 return;
520         memset(dt, 0, sizeof(struct dtl_entry));
521         dt->dispatch_reason = 7;
522         dt->processor_id = vc->pcpu + vcpu->arch.ptid;
523         dt->timebase = now + vc->tb_offset;
524         dt->enqueue_to_dispatch_time = stolen;
525         dt->srr0 = kvmppc_get_pc(vcpu);
526         dt->srr1 = vcpu->arch.shregs.msr;
527         ++dt;
528         if (dt == vcpu->arch.dtl.pinned_end)
529                 dt = vcpu->arch.dtl.pinned_addr;
530         vcpu->arch.dtl_ptr = dt;
531         /* order writing *dt vs. writing vpa->dtl_idx */
532         smp_wmb();
533         vpa->dtl_idx = ++vcpu->arch.dtl_index;
534         vcpu->arch.dtl.dirty = true;
535 }
536
537 int kvmppc_pseries_do_hcall(struct kvm_vcpu *vcpu)
538 {
539         unsigned long req = kvmppc_get_gpr(vcpu, 3);
540         unsigned long target, ret = H_SUCCESS;
541         struct kvm_vcpu *tvcpu;
542         int idx, rc;
543
544         switch (req) {
545         case H_ENTER:
546                 idx = srcu_read_lock(&vcpu->kvm->srcu);
547                 ret = kvmppc_virtmode_h_enter(vcpu, kvmppc_get_gpr(vcpu, 4),
548                                               kvmppc_get_gpr(vcpu, 5),
549                                               kvmppc_get_gpr(vcpu, 6),
550                                               kvmppc_get_gpr(vcpu, 7));
551                 srcu_read_unlock(&vcpu->kvm->srcu, idx);
552                 break;
553         case H_CEDE:
554                 break;
555         case H_PROD:
556                 target = kvmppc_get_gpr(vcpu, 4);
557                 tvcpu = kvmppc_find_vcpu(vcpu->kvm, target);
558                 if (!tvcpu) {
559                         ret = H_PARAMETER;
560                         break;
561                 }
562                 tvcpu->arch.prodded = 1;
563                 smp_mb();
564                 if (vcpu->arch.ceded) {
565                         if (waitqueue_active(&vcpu->wq)) {
566                                 wake_up_interruptible(&vcpu->wq);
567                                 vcpu->stat.halt_wakeup++;
568                         }
569                 }
570                 break;
571         case H_CONFER:
572                 target = kvmppc_get_gpr(vcpu, 4);
573                 if (target == -1)
574                         break;
575                 tvcpu = kvmppc_find_vcpu(vcpu->kvm, target);
576                 if (!tvcpu) {
577                         ret = H_PARAMETER;
578                         break;
579                 }
580                 kvm_vcpu_yield_to(tvcpu);
581                 break;
582         case H_REGISTER_VPA:
583                 ret = do_h_register_vpa(vcpu, kvmppc_get_gpr(vcpu, 4),
584                                         kvmppc_get_gpr(vcpu, 5),
585                                         kvmppc_get_gpr(vcpu, 6));
586                 break;
587         case H_RTAS:
588                 if (list_empty(&vcpu->kvm->arch.rtas_tokens))
589                         return RESUME_HOST;
590
591                 rc = kvmppc_rtas_hcall(vcpu);
592
593                 if (rc == -ENOENT)
594                         return RESUME_HOST;
595                 else if (rc == 0)
596                         break;
597
598                 /* Send the error out to userspace via KVM_RUN */
599                 return rc;
600
601         case H_XIRR:
602         case H_CPPR:
603         case H_EOI:
604         case H_IPI:
605         case H_IPOLL:
606         case H_XIRR_X:
607                 if (kvmppc_xics_enabled(vcpu)) {
608                         ret = kvmppc_xics_hcall(vcpu, req);
609                         break;
610                 } /* fallthrough */
611         default:
612                 return RESUME_HOST;
613         }
614         kvmppc_set_gpr(vcpu, 3, ret);
615         vcpu->arch.hcall_needed = 0;
616         return RESUME_GUEST;
617 }
618
619 static int kvmppc_handle_exit_hv(struct kvm_run *run, struct kvm_vcpu *vcpu,
620                                  struct task_struct *tsk)
621 {
622         int r = RESUME_HOST;
623
624         vcpu->stat.sum_exits++;
625
626         run->exit_reason = KVM_EXIT_UNKNOWN;
627         run->ready_for_interrupt_injection = 1;
628         switch (vcpu->arch.trap) {
629         /* We're good on these - the host merely wanted to get our attention */
630         case BOOK3S_INTERRUPT_HV_DECREMENTER:
631                 vcpu->stat.dec_exits++;
632                 r = RESUME_GUEST;
633                 break;
634         case BOOK3S_INTERRUPT_EXTERNAL:
635                 vcpu->stat.ext_intr_exits++;
636                 r = RESUME_GUEST;
637                 break;
638         case BOOK3S_INTERRUPT_PERFMON:
639                 r = RESUME_GUEST;
640                 break;
641         case BOOK3S_INTERRUPT_MACHINE_CHECK:
642                 /*
643                  * Deliver a machine check interrupt to the guest.
644                  * We have to do this, even if the host has handled the
645                  * machine check, because machine checks use SRR0/1 and
646                  * the interrupt might have trashed guest state in them.
647                  */
648                 kvmppc_book3s_queue_irqprio(vcpu,
649                                             BOOK3S_INTERRUPT_MACHINE_CHECK);
650                 r = RESUME_GUEST;
651                 break;
652         case BOOK3S_INTERRUPT_PROGRAM:
653         {
654                 ulong flags;
655                 /*
656                  * Normally program interrupts are delivered directly
657                  * to the guest by the hardware, but we can get here
658                  * as a result of a hypervisor emulation interrupt
659                  * (e40) getting turned into a 700 by BML RTAS.
660                  */
661                 flags = vcpu->arch.shregs.msr & 0x1f0000ull;
662                 kvmppc_core_queue_program(vcpu, flags);
663                 r = RESUME_GUEST;
664                 break;
665         }
666         case BOOK3S_INTERRUPT_SYSCALL:
667         {
668                 /* hcall - punt to userspace */
669                 int i;
670
671                 if (vcpu->arch.shregs.msr & MSR_PR) {
672                         /* sc 1 from userspace - reflect to guest syscall */
673                         kvmppc_book3s_queue_irqprio(vcpu, BOOK3S_INTERRUPT_SYSCALL);
674                         r = RESUME_GUEST;
675                         break;
676                 }
677                 run->papr_hcall.nr = kvmppc_get_gpr(vcpu, 3);
678                 for (i = 0; i < 9; ++i)
679                         run->papr_hcall.args[i] = kvmppc_get_gpr(vcpu, 4 + i);
680                 run->exit_reason = KVM_EXIT_PAPR_HCALL;
681                 vcpu->arch.hcall_needed = 1;
682                 r = RESUME_HOST;
683                 break;
684         }
685         /*
686          * We get these next two if the guest accesses a page which it thinks
687          * it has mapped but which is not actually present, either because
688          * it is for an emulated I/O device or because the corresonding
689          * host page has been paged out.  Any other HDSI/HISI interrupts
690          * have been handled already.
691          */
692         case BOOK3S_INTERRUPT_H_DATA_STORAGE:
693                 r = RESUME_PAGE_FAULT;
694                 break;
695         case BOOK3S_INTERRUPT_H_INST_STORAGE:
696                 vcpu->arch.fault_dar = kvmppc_get_pc(vcpu);
697                 vcpu->arch.fault_dsisr = 0;
698                 r = RESUME_PAGE_FAULT;
699                 break;
700         /*
701          * This occurs if the guest executes an illegal instruction.
702          * We just generate a program interrupt to the guest, since
703          * we don't emulate any guest instructions at this stage.
704          */
705         case BOOK3S_INTERRUPT_H_EMUL_ASSIST:
706                 kvmppc_core_queue_program(vcpu, 0x80000);
707                 r = RESUME_GUEST;
708                 break;
709         default:
710                 kvmppc_dump_regs(vcpu);
711                 printk(KERN_EMERG "trap=0x%x | pc=0x%lx | msr=0x%llx\n",
712                         vcpu->arch.trap, kvmppc_get_pc(vcpu),
713                         vcpu->arch.shregs.msr);
714                 run->hw.hardware_exit_reason = vcpu->arch.trap;
715                 r = RESUME_HOST;
716                 break;
717         }
718
719         return r;
720 }
721
722 static int kvm_arch_vcpu_ioctl_get_sregs_hv(struct kvm_vcpu *vcpu,
723                                             struct kvm_sregs *sregs)
724 {
725         int i;
726
727         memset(sregs, 0, sizeof(struct kvm_sregs));
728         sregs->pvr = vcpu->arch.pvr;
729         for (i = 0; i < vcpu->arch.slb_max; i++) {
730                 sregs->u.s.ppc64.slb[i].slbe = vcpu->arch.slb[i].orige;
731                 sregs->u.s.ppc64.slb[i].slbv = vcpu->arch.slb[i].origv;
732         }
733
734         return 0;
735 }
736
737 static int kvm_arch_vcpu_ioctl_set_sregs_hv(struct kvm_vcpu *vcpu,
738                                             struct kvm_sregs *sregs)
739 {
740         int i, j;
741
742         kvmppc_set_pvr_hv(vcpu, sregs->pvr);
743
744         j = 0;
745         for (i = 0; i < vcpu->arch.slb_nr; i++) {
746                 if (sregs->u.s.ppc64.slb[i].slbe & SLB_ESID_V) {
747                         vcpu->arch.slb[j].orige = sregs->u.s.ppc64.slb[i].slbe;
748                         vcpu->arch.slb[j].origv = sregs->u.s.ppc64.slb[i].slbv;
749                         ++j;
750                 }
751         }
752         vcpu->arch.slb_max = j;
753
754         return 0;
755 }
756
757 static void kvmppc_set_lpcr(struct kvm_vcpu *vcpu, u64 new_lpcr)
758 {
759         struct kvmppc_vcore *vc = vcpu->arch.vcore;
760         u64 mask;
761
762         spin_lock(&vc->lock);
763         /*
764          * Userspace can only modify DPFD (default prefetch depth),
765          * ILE (interrupt little-endian) and TC (translation control).
766          */
767         mask = LPCR_DPFD | LPCR_ILE | LPCR_TC;
768         vc->lpcr = (vc->lpcr & ~mask) | (new_lpcr & mask);
769         spin_unlock(&vc->lock);
770 }
771
772 static int kvmppc_get_one_reg_hv(struct kvm_vcpu *vcpu, u64 id,
773                                  union kvmppc_one_reg *val)
774 {
775         int r = 0;
776         long int i;
777
778         switch (id) {
779         case KVM_REG_PPC_HIOR:
780                 *val = get_reg_val(id, 0);
781                 break;
782         case KVM_REG_PPC_DABR:
783                 *val = get_reg_val(id, vcpu->arch.dabr);
784                 break;
785         case KVM_REG_PPC_DSCR:
786                 *val = get_reg_val(id, vcpu->arch.dscr);
787                 break;
788         case KVM_REG_PPC_PURR:
789                 *val = get_reg_val(id, vcpu->arch.purr);
790                 break;
791         case KVM_REG_PPC_SPURR:
792                 *val = get_reg_val(id, vcpu->arch.spurr);
793                 break;
794         case KVM_REG_PPC_AMR:
795                 *val = get_reg_val(id, vcpu->arch.amr);
796                 break;
797         case KVM_REG_PPC_UAMOR:
798                 *val = get_reg_val(id, vcpu->arch.uamor);
799                 break;
800         case KVM_REG_PPC_MMCR0 ... KVM_REG_PPC_MMCRA:
801                 i = id - KVM_REG_PPC_MMCR0;
802                 *val = get_reg_val(id, vcpu->arch.mmcr[i]);
803                 break;
804         case KVM_REG_PPC_PMC1 ... KVM_REG_PPC_PMC8:
805                 i = id - KVM_REG_PPC_PMC1;
806                 *val = get_reg_val(id, vcpu->arch.pmc[i]);
807                 break;
808         case KVM_REG_PPC_SIAR:
809                 *val = get_reg_val(id, vcpu->arch.siar);
810                 break;
811         case KVM_REG_PPC_SDAR:
812                 *val = get_reg_val(id, vcpu->arch.sdar);
813                 break;
814 #ifdef CONFIG_VSX
815         case KVM_REG_PPC_FPR0 ... KVM_REG_PPC_FPR31:
816                 if (cpu_has_feature(CPU_FTR_VSX)) {
817                         /* VSX => FP reg i is stored in arch.vsr[2*i] */
818                         long int i = id - KVM_REG_PPC_FPR0;
819                         *val = get_reg_val(id, vcpu->arch.vsr[2 * i]);
820                 } else {
821                         /* let generic code handle it */
822                         r = -EINVAL;
823                 }
824                 break;
825         case KVM_REG_PPC_VSR0 ... KVM_REG_PPC_VSR31:
826                 if (cpu_has_feature(CPU_FTR_VSX)) {
827                         long int i = id - KVM_REG_PPC_VSR0;
828                         val->vsxval[0] = vcpu->arch.vsr[2 * i];
829                         val->vsxval[1] = vcpu->arch.vsr[2 * i + 1];
830                 } else {
831                         r = -ENXIO;
832                 }
833                 break;
834 #endif /* CONFIG_VSX */
835         case KVM_REG_PPC_VPA_ADDR:
836                 spin_lock(&vcpu->arch.vpa_update_lock);
837                 *val = get_reg_val(id, vcpu->arch.vpa.next_gpa);
838                 spin_unlock(&vcpu->arch.vpa_update_lock);
839                 break;
840         case KVM_REG_PPC_VPA_SLB:
841                 spin_lock(&vcpu->arch.vpa_update_lock);
842                 val->vpaval.addr = vcpu->arch.slb_shadow.next_gpa;
843                 val->vpaval.length = vcpu->arch.slb_shadow.len;
844                 spin_unlock(&vcpu->arch.vpa_update_lock);
845                 break;
846         case KVM_REG_PPC_VPA_DTL:
847                 spin_lock(&vcpu->arch.vpa_update_lock);
848                 val->vpaval.addr = vcpu->arch.dtl.next_gpa;
849                 val->vpaval.length = vcpu->arch.dtl.len;
850                 spin_unlock(&vcpu->arch.vpa_update_lock);
851                 break;
852         case KVM_REG_PPC_TB_OFFSET:
853                 *val = get_reg_val(id, vcpu->arch.vcore->tb_offset);
854                 break;
855         case KVM_REG_PPC_LPCR:
856                 *val = get_reg_val(id, vcpu->arch.vcore->lpcr);
857                 break;
858         case KVM_REG_PPC_PPR:
859                 *val = get_reg_val(id, vcpu->arch.ppr);
860                 break;
861         case KVM_REG_PPC_ARCH_COMPAT:
862                 *val = get_reg_val(id, vcpu->arch.vcore->arch_compat);
863                 break;
864         default:
865                 r = -EINVAL;
866                 break;
867         }
868
869         return r;
870 }
871
872 static int kvmppc_set_one_reg_hv(struct kvm_vcpu *vcpu, u64 id,
873                                  union kvmppc_one_reg *val)
874 {
875         int r = 0;
876         long int i;
877         unsigned long addr, len;
878
879         switch (id) {
880         case KVM_REG_PPC_HIOR:
881                 /* Only allow this to be set to zero */
882                 if (set_reg_val(id, *val))
883                         r = -EINVAL;
884                 break;
885         case KVM_REG_PPC_DABR:
886                 vcpu->arch.dabr = set_reg_val(id, *val);
887                 break;
888         case KVM_REG_PPC_DSCR:
889                 vcpu->arch.dscr = set_reg_val(id, *val);
890                 break;
891         case KVM_REG_PPC_PURR:
892                 vcpu->arch.purr = set_reg_val(id, *val);
893                 break;
894         case KVM_REG_PPC_SPURR:
895                 vcpu->arch.spurr = set_reg_val(id, *val);
896                 break;
897         case KVM_REG_PPC_AMR:
898                 vcpu->arch.amr = set_reg_val(id, *val);
899                 break;
900         case KVM_REG_PPC_UAMOR:
901                 vcpu->arch.uamor = set_reg_val(id, *val);
902                 break;
903         case KVM_REG_PPC_MMCR0 ... KVM_REG_PPC_MMCRA:
904                 i = id - KVM_REG_PPC_MMCR0;
905                 vcpu->arch.mmcr[i] = set_reg_val(id, *val);
906                 break;
907         case KVM_REG_PPC_PMC1 ... KVM_REG_PPC_PMC8:
908                 i = id - KVM_REG_PPC_PMC1;
909                 vcpu->arch.pmc[i] = set_reg_val(id, *val);
910                 break;
911         case KVM_REG_PPC_SIAR:
912                 vcpu->arch.siar = set_reg_val(id, *val);
913                 break;
914         case KVM_REG_PPC_SDAR:
915                 vcpu->arch.sdar = set_reg_val(id, *val);
916                 break;
917 #ifdef CONFIG_VSX
918         case KVM_REG_PPC_FPR0 ... KVM_REG_PPC_FPR31:
919                 if (cpu_has_feature(CPU_FTR_VSX)) {
920                         /* VSX => FP reg i is stored in arch.vsr[2*i] */
921                         long int i = id - KVM_REG_PPC_FPR0;
922                         vcpu->arch.vsr[2 * i] = set_reg_val(id, *val);
923                 } else {
924                         /* let generic code handle it */
925                         r = -EINVAL;
926                 }
927                 break;
928         case KVM_REG_PPC_VSR0 ... KVM_REG_PPC_VSR31:
929                 if (cpu_has_feature(CPU_FTR_VSX)) {
930                         long int i = id - KVM_REG_PPC_VSR0;
931                         vcpu->arch.vsr[2 * i] = val->vsxval[0];
932                         vcpu->arch.vsr[2 * i + 1] = val->vsxval[1];
933                 } else {
934                         r = -ENXIO;
935                 }
936                 break;
937 #endif /* CONFIG_VSX */
938         case KVM_REG_PPC_VPA_ADDR:
939                 addr = set_reg_val(id, *val);
940                 r = -EINVAL;
941                 if (!addr && (vcpu->arch.slb_shadow.next_gpa ||
942                               vcpu->arch.dtl.next_gpa))
943                         break;
944                 r = set_vpa(vcpu, &vcpu->arch.vpa, addr, sizeof(struct lppaca));
945                 break;
946         case KVM_REG_PPC_VPA_SLB:
947                 addr = val->vpaval.addr;
948                 len = val->vpaval.length;
949                 r = -EINVAL;
950                 if (addr && !vcpu->arch.vpa.next_gpa)
951                         break;
952                 r = set_vpa(vcpu, &vcpu->arch.slb_shadow, addr, len);
953                 break;
954         case KVM_REG_PPC_VPA_DTL:
955                 addr = val->vpaval.addr;
956                 len = val->vpaval.length;
957                 r = -EINVAL;
958                 if (addr && (len < sizeof(struct dtl_entry) ||
959                              !vcpu->arch.vpa.next_gpa))
960                         break;
961                 len -= len % sizeof(struct dtl_entry);
962                 r = set_vpa(vcpu, &vcpu->arch.dtl, addr, len);
963                 break;
964         case KVM_REG_PPC_TB_OFFSET:
965                 /* round up to multiple of 2^24 */
966                 vcpu->arch.vcore->tb_offset =
967                         ALIGN(set_reg_val(id, *val), 1UL << 24);
968                 break;
969         case KVM_REG_PPC_LPCR:
970                 kvmppc_set_lpcr(vcpu, set_reg_val(id, *val));
971                 break;
972         case KVM_REG_PPC_PPR:
973                 vcpu->arch.ppr = set_reg_val(id, *val);
974                 break;
975         case KVM_REG_PPC_ARCH_COMPAT:
976                 r = kvmppc_set_arch_compat(vcpu, set_reg_val(id, *val));
977                 break;
978         default:
979                 r = -EINVAL;
980                 break;
981         }
982
983         return r;
984 }
985
986 static struct kvm_vcpu *kvmppc_core_vcpu_create_hv(struct kvm *kvm,
987                                                    unsigned int id)
988 {
989         struct kvm_vcpu *vcpu;
990         int err = -EINVAL;
991         int core;
992         struct kvmppc_vcore *vcore;
993
994         core = id / threads_per_core;
995         if (core >= KVM_MAX_VCORES)
996                 goto out;
997
998         err = -ENOMEM;
999         vcpu = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL);
1000         if (!vcpu)
1001                 goto out;
1002
1003         err = kvm_vcpu_init(vcpu, kvm, id);
1004         if (err)
1005                 goto free_vcpu;
1006
1007         vcpu->arch.shared = &vcpu->arch.shregs;
1008         vcpu->arch.mmcr[0] = MMCR0_FC;
1009         vcpu->arch.ctrl = CTRL_RUNLATCH;
1010         /* default to host PVR, since we can't spoof it */
1011         kvmppc_set_pvr_hv(vcpu, mfspr(SPRN_PVR));
1012         spin_lock_init(&vcpu->arch.vpa_update_lock);
1013         spin_lock_init(&vcpu->arch.tbacct_lock);
1014         vcpu->arch.busy_preempt = TB_NIL;
1015
1016         kvmppc_mmu_book3s_hv_init(vcpu);
1017
1018         vcpu->arch.state = KVMPPC_VCPU_NOTREADY;
1019
1020         init_waitqueue_head(&vcpu->arch.cpu_run);
1021
1022         mutex_lock(&kvm->lock);
1023         vcore = kvm->arch.vcores[core];
1024         if (!vcore) {
1025                 vcore = kzalloc(sizeof(struct kvmppc_vcore), GFP_KERNEL);
1026                 if (vcore) {
1027                         INIT_LIST_HEAD(&vcore->runnable_threads);
1028                         spin_lock_init(&vcore->lock);
1029                         init_waitqueue_head(&vcore->wq);
1030                         vcore->preempt_tb = TB_NIL;
1031                         vcore->lpcr = kvm->arch.lpcr;
1032                 }
1033                 kvm->arch.vcores[core] = vcore;
1034                 kvm->arch.online_vcores++;
1035         }
1036         mutex_unlock(&kvm->lock);
1037
1038         if (!vcore)
1039                 goto free_vcpu;
1040
1041         spin_lock(&vcore->lock);
1042         ++vcore->num_threads;
1043         spin_unlock(&vcore->lock);
1044         vcpu->arch.vcore = vcore;
1045
1046         vcpu->arch.cpu_type = KVM_CPU_3S_64;
1047         kvmppc_sanity_check(vcpu);
1048
1049         return vcpu;
1050
1051 free_vcpu:
1052         kmem_cache_free(kvm_vcpu_cache, vcpu);
1053 out:
1054         return ERR_PTR(err);
1055 }
1056
1057 static void unpin_vpa(struct kvm *kvm, struct kvmppc_vpa *vpa)
1058 {
1059         if (vpa->pinned_addr)
1060                 kvmppc_unpin_guest_page(kvm, vpa->pinned_addr, vpa->gpa,
1061                                         vpa->dirty);
1062 }
1063
1064 static void kvmppc_core_vcpu_free_hv(struct kvm_vcpu *vcpu)
1065 {
1066         spin_lock(&vcpu->arch.vpa_update_lock);
1067         unpin_vpa(vcpu->kvm, &vcpu->arch.dtl);
1068         unpin_vpa(vcpu->kvm, &vcpu->arch.slb_shadow);
1069         unpin_vpa(vcpu->kvm, &vcpu->arch.vpa);
1070         spin_unlock(&vcpu->arch.vpa_update_lock);
1071         kvm_vcpu_uninit(vcpu);
1072         kmem_cache_free(kvm_vcpu_cache, vcpu);
1073 }
1074
1075 static int kvmppc_core_check_requests_hv(struct kvm_vcpu *vcpu)
1076 {
1077         /* Indicate we want to get back into the guest */
1078         return 1;
1079 }
1080
1081 static void kvmppc_set_timer(struct kvm_vcpu *vcpu)
1082 {
1083         unsigned long dec_nsec, now;
1084
1085         now = get_tb();
1086         if (now > vcpu->arch.dec_expires) {
1087                 /* decrementer has already gone negative */
1088                 kvmppc_core_queue_dec(vcpu);
1089                 kvmppc_core_prepare_to_enter(vcpu);
1090                 return;
1091         }
1092         dec_nsec = (vcpu->arch.dec_expires - now) * NSEC_PER_SEC
1093                    / tb_ticks_per_sec;
1094         hrtimer_start(&vcpu->arch.dec_timer, ktime_set(0, dec_nsec),
1095                       HRTIMER_MODE_REL);
1096         vcpu->arch.timer_running = 1;
1097 }
1098
1099 static void kvmppc_end_cede(struct kvm_vcpu *vcpu)
1100 {
1101         vcpu->arch.ceded = 0;
1102         if (vcpu->arch.timer_running) {
1103                 hrtimer_try_to_cancel(&vcpu->arch.dec_timer);
1104                 vcpu->arch.timer_running = 0;
1105         }
1106 }
1107
1108 extern int __kvmppc_vcore_entry(struct kvm_run *kvm_run, struct kvm_vcpu *vcpu);
1109
1110 static void kvmppc_remove_runnable(struct kvmppc_vcore *vc,
1111                                    struct kvm_vcpu *vcpu)
1112 {
1113         u64 now;
1114
1115         if (vcpu->arch.state != KVMPPC_VCPU_RUNNABLE)
1116                 return;
1117         spin_lock(&vcpu->arch.tbacct_lock);
1118         now = mftb();
1119         vcpu->arch.busy_stolen += vcore_stolen_time(vc, now) -
1120                 vcpu->arch.stolen_logged;
1121         vcpu->arch.busy_preempt = now;
1122         vcpu->arch.state = KVMPPC_VCPU_BUSY_IN_HOST;
1123         spin_unlock(&vcpu->arch.tbacct_lock);
1124         --vc->n_runnable;
1125         list_del(&vcpu->arch.run_list);
1126 }
1127
1128 static int kvmppc_grab_hwthread(int cpu)
1129 {
1130         struct paca_struct *tpaca;
1131         long timeout = 1000;
1132
1133         tpaca = &paca[cpu];
1134
1135         /* Ensure the thread won't go into the kernel if it wakes */
1136         tpaca->kvm_hstate.hwthread_req = 1;
1137         tpaca->kvm_hstate.kvm_vcpu = NULL;
1138
1139         /*
1140          * If the thread is already executing in the kernel (e.g. handling
1141          * a stray interrupt), wait for it to get back to nap mode.
1142          * The smp_mb() is to ensure that our setting of hwthread_req
1143          * is visible before we look at hwthread_state, so if this
1144          * races with the code at system_reset_pSeries and the thread
1145          * misses our setting of hwthread_req, we are sure to see its
1146          * setting of hwthread_state, and vice versa.
1147          */
1148         smp_mb();
1149         while (tpaca->kvm_hstate.hwthread_state == KVM_HWTHREAD_IN_KERNEL) {
1150                 if (--timeout <= 0) {
1151                         pr_err("KVM: couldn't grab cpu %d\n", cpu);
1152                         return -EBUSY;
1153                 }
1154                 udelay(1);
1155         }
1156         return 0;
1157 }
1158
1159 static void kvmppc_release_hwthread(int cpu)
1160 {
1161         struct paca_struct *tpaca;
1162
1163         tpaca = &paca[cpu];
1164         tpaca->kvm_hstate.hwthread_req = 0;
1165         tpaca->kvm_hstate.kvm_vcpu = NULL;
1166 }
1167
1168 static void kvmppc_start_thread(struct kvm_vcpu *vcpu)
1169 {
1170         int cpu;
1171         struct paca_struct *tpaca;
1172         struct kvmppc_vcore *vc = vcpu->arch.vcore;
1173
1174         if (vcpu->arch.timer_running) {
1175                 hrtimer_try_to_cancel(&vcpu->arch.dec_timer);
1176                 vcpu->arch.timer_running = 0;
1177         }
1178         cpu = vc->pcpu + vcpu->arch.ptid;
1179         tpaca = &paca[cpu];
1180         tpaca->kvm_hstate.kvm_vcpu = vcpu;
1181         tpaca->kvm_hstate.kvm_vcore = vc;
1182         tpaca->kvm_hstate.napping = 0;
1183         vcpu->cpu = vc->pcpu;
1184         smp_wmb();
1185 #if defined(CONFIG_PPC_ICP_NATIVE) && defined(CONFIG_SMP)
1186         if (vcpu->arch.ptid) {
1187                 xics_wake_cpu(cpu);
1188                 ++vc->n_woken;
1189         }
1190 #endif
1191 }
1192
1193 static void kvmppc_wait_for_nap(struct kvmppc_vcore *vc)
1194 {
1195         int i;
1196
1197         HMT_low();
1198         i = 0;
1199         while (vc->nap_count < vc->n_woken) {
1200                 if (++i >= 1000000) {
1201                         pr_err("kvmppc_wait_for_nap timeout %d %d\n",
1202                                vc->nap_count, vc->n_woken);
1203                         break;
1204                 }
1205                 cpu_relax();
1206         }
1207         HMT_medium();
1208 }
1209
1210 /*
1211  * Check that we are on thread 0 and that any other threads in
1212  * this core are off-line.  Then grab the threads so they can't
1213  * enter the kernel.
1214  */
1215 static int on_primary_thread(void)
1216 {
1217         int cpu = smp_processor_id();
1218         int thr = cpu_thread_in_core(cpu);
1219
1220         if (thr)
1221                 return 0;
1222         while (++thr < threads_per_core)
1223                 if (cpu_online(cpu + thr))
1224                         return 0;
1225
1226         /* Grab all hw threads so they can't go into the kernel */
1227         for (thr = 1; thr < threads_per_core; ++thr) {
1228                 if (kvmppc_grab_hwthread(cpu + thr)) {
1229                         /* Couldn't grab one; let the others go */
1230                         do {
1231                                 kvmppc_release_hwthread(cpu + thr);
1232                         } while (--thr > 0);
1233                         return 0;
1234                 }
1235         }
1236         return 1;
1237 }
1238
1239 /*
1240  * Run a set of guest threads on a physical core.
1241  * Called with vc->lock held.
1242  */
1243 static void kvmppc_run_core(struct kvmppc_vcore *vc)
1244 {
1245         struct kvm_vcpu *vcpu, *vcpu0, *vnext;
1246         long ret;
1247         u64 now;
1248         int ptid, i, need_vpa_update;
1249         int srcu_idx;
1250         struct kvm_vcpu *vcpus_to_update[threads_per_core];
1251
1252         /* don't start if any threads have a signal pending */
1253         need_vpa_update = 0;
1254         list_for_each_entry(vcpu, &vc->runnable_threads, arch.run_list) {
1255                 if (signal_pending(vcpu->arch.run_task))
1256                         return;
1257                 if (vcpu->arch.vpa.update_pending ||
1258                     vcpu->arch.slb_shadow.update_pending ||
1259                     vcpu->arch.dtl.update_pending)
1260                         vcpus_to_update[need_vpa_update++] = vcpu;
1261         }
1262
1263         /*
1264          * Initialize *vc, in particular vc->vcore_state, so we can
1265          * drop the vcore lock if necessary.
1266          */
1267         vc->n_woken = 0;
1268         vc->nap_count = 0;
1269         vc->entry_exit_count = 0;
1270         vc->vcore_state = VCORE_STARTING;
1271         vc->in_guest = 0;
1272         vc->napping_threads = 0;
1273
1274         /*
1275          * Updating any of the vpas requires calling kvmppc_pin_guest_page,
1276          * which can't be called with any spinlocks held.
1277          */
1278         if (need_vpa_update) {
1279                 spin_unlock(&vc->lock);
1280                 for (i = 0; i < need_vpa_update; ++i)
1281                         kvmppc_update_vpas(vcpus_to_update[i]);
1282                 spin_lock(&vc->lock);
1283         }
1284
1285         /*
1286          * Assign physical thread IDs, first to non-ceded vcpus
1287          * and then to ceded ones.
1288          */
1289         ptid = 0;
1290         vcpu0 = NULL;
1291         list_for_each_entry(vcpu, &vc->runnable_threads, arch.run_list) {
1292                 if (!vcpu->arch.ceded) {
1293                         if (!ptid)
1294                                 vcpu0 = vcpu;
1295                         vcpu->arch.ptid = ptid++;
1296                 }
1297         }
1298         if (!vcpu0)
1299                 goto out;       /* nothing to run; should never happen */
1300         list_for_each_entry(vcpu, &vc->runnable_threads, arch.run_list)
1301                 if (vcpu->arch.ceded)
1302                         vcpu->arch.ptid = ptid++;
1303
1304         /*
1305          * Make sure we are running on thread 0, and that
1306          * secondary threads are offline.
1307          */
1308         if (threads_per_core > 1 && !on_primary_thread()) {
1309                 list_for_each_entry(vcpu, &vc->runnable_threads, arch.run_list)
1310                         vcpu->arch.ret = -EBUSY;
1311                 goto out;
1312         }
1313
1314         vc->pcpu = smp_processor_id();
1315         list_for_each_entry(vcpu, &vc->runnable_threads, arch.run_list) {
1316                 kvmppc_start_thread(vcpu);
1317                 kvmppc_create_dtl_entry(vcpu, vc);
1318         }
1319
1320         vc->vcore_state = VCORE_RUNNING;
1321         preempt_disable();
1322         spin_unlock(&vc->lock);
1323
1324         kvm_guest_enter();
1325
1326         srcu_idx = srcu_read_lock(&vcpu0->kvm->srcu);
1327
1328         __kvmppc_vcore_entry(NULL, vcpu0);
1329
1330         spin_lock(&vc->lock);
1331         /* disable sending of IPIs on virtual external irqs */
1332         list_for_each_entry(vcpu, &vc->runnable_threads, arch.run_list)
1333                 vcpu->cpu = -1;
1334         /* wait for secondary threads to finish writing their state to memory */
1335         if (vc->nap_count < vc->n_woken)
1336                 kvmppc_wait_for_nap(vc);
1337         for (i = 0; i < threads_per_core; ++i)
1338                 kvmppc_release_hwthread(vc->pcpu + i);
1339         /* prevent other vcpu threads from doing kvmppc_start_thread() now */
1340         vc->vcore_state = VCORE_EXITING;
1341         spin_unlock(&vc->lock);
1342
1343         srcu_read_unlock(&vcpu0->kvm->srcu, srcu_idx);
1344
1345         /* make sure updates to secondary vcpu structs are visible now */
1346         smp_mb();
1347         kvm_guest_exit();
1348
1349         preempt_enable();
1350         kvm_resched(vcpu);
1351
1352         spin_lock(&vc->lock);
1353         now = get_tb();
1354         list_for_each_entry(vcpu, &vc->runnable_threads, arch.run_list) {
1355                 /* cancel pending dec exception if dec is positive */
1356                 if (now < vcpu->arch.dec_expires &&
1357                     kvmppc_core_pending_dec(vcpu))
1358                         kvmppc_core_dequeue_dec(vcpu);
1359
1360                 ret = RESUME_GUEST;
1361                 if (vcpu->arch.trap)
1362                         ret = kvmppc_handle_exit_hv(vcpu->arch.kvm_run, vcpu,
1363                                                     vcpu->arch.run_task);
1364
1365                 vcpu->arch.ret = ret;
1366                 vcpu->arch.trap = 0;
1367
1368                 if (vcpu->arch.ceded) {
1369                         if (ret != RESUME_GUEST)
1370                                 kvmppc_end_cede(vcpu);
1371                         else
1372                                 kvmppc_set_timer(vcpu);
1373                 }
1374         }
1375
1376  out:
1377         vc->vcore_state = VCORE_INACTIVE;
1378         list_for_each_entry_safe(vcpu, vnext, &vc->runnable_threads,
1379                                  arch.run_list) {
1380                 if (vcpu->arch.ret != RESUME_GUEST) {
1381                         kvmppc_remove_runnable(vc, vcpu);
1382                         wake_up(&vcpu->arch.cpu_run);
1383                 }
1384         }
1385 }
1386
1387 /*
1388  * Wait for some other vcpu thread to execute us, and
1389  * wake us up when we need to handle something in the host.
1390  */
1391 static void kvmppc_wait_for_exec(struct kvm_vcpu *vcpu, int wait_state)
1392 {
1393         DEFINE_WAIT(wait);
1394
1395         prepare_to_wait(&vcpu->arch.cpu_run, &wait, wait_state);
1396         if (vcpu->arch.state == KVMPPC_VCPU_RUNNABLE)
1397                 schedule();
1398         finish_wait(&vcpu->arch.cpu_run, &wait);
1399 }
1400
1401 /*
1402  * All the vcpus in this vcore are idle, so wait for a decrementer
1403  * or external interrupt to one of the vcpus.  vc->lock is held.
1404  */
1405 static void kvmppc_vcore_blocked(struct kvmppc_vcore *vc)
1406 {
1407         DEFINE_WAIT(wait);
1408
1409         prepare_to_wait(&vc->wq, &wait, TASK_INTERRUPTIBLE);
1410         vc->vcore_state = VCORE_SLEEPING;
1411         spin_unlock(&vc->lock);
1412         schedule();
1413         finish_wait(&vc->wq, &wait);
1414         spin_lock(&vc->lock);
1415         vc->vcore_state = VCORE_INACTIVE;
1416 }
1417
1418 static int kvmppc_run_vcpu(struct kvm_run *kvm_run, struct kvm_vcpu *vcpu)
1419 {
1420         int n_ceded;
1421         struct kvmppc_vcore *vc;
1422         struct kvm_vcpu *v, *vn;
1423
1424         kvm_run->exit_reason = 0;
1425         vcpu->arch.ret = RESUME_GUEST;
1426         vcpu->arch.trap = 0;
1427         kvmppc_update_vpas(vcpu);
1428
1429         /*
1430          * Synchronize with other threads in this virtual core
1431          */
1432         vc = vcpu->arch.vcore;
1433         spin_lock(&vc->lock);
1434         vcpu->arch.ceded = 0;
1435         vcpu->arch.run_task = current;
1436         vcpu->arch.kvm_run = kvm_run;
1437         vcpu->arch.stolen_logged = vcore_stolen_time(vc, mftb());
1438         vcpu->arch.state = KVMPPC_VCPU_RUNNABLE;
1439         vcpu->arch.busy_preempt = TB_NIL;
1440         list_add_tail(&vcpu->arch.run_list, &vc->runnable_threads);
1441         ++vc->n_runnable;
1442
1443         /*
1444          * This happens the first time this is called for a vcpu.
1445          * If the vcore is already running, we may be able to start
1446          * this thread straight away and have it join in.
1447          */
1448         if (!signal_pending(current)) {
1449                 if (vc->vcore_state == VCORE_RUNNING &&
1450                     VCORE_EXIT_COUNT(vc) == 0) {
1451                         vcpu->arch.ptid = vc->n_runnable - 1;
1452                         kvmppc_create_dtl_entry(vcpu, vc);
1453                         kvmppc_start_thread(vcpu);
1454                 } else if (vc->vcore_state == VCORE_SLEEPING) {
1455                         wake_up(&vc->wq);
1456                 }
1457
1458         }
1459
1460         while (vcpu->arch.state == KVMPPC_VCPU_RUNNABLE &&
1461                !signal_pending(current)) {
1462                 if (vc->vcore_state != VCORE_INACTIVE) {
1463                         spin_unlock(&vc->lock);
1464                         kvmppc_wait_for_exec(vcpu, TASK_INTERRUPTIBLE);
1465                         spin_lock(&vc->lock);
1466                         continue;
1467                 }
1468                 list_for_each_entry_safe(v, vn, &vc->runnable_threads,
1469                                          arch.run_list) {
1470                         kvmppc_core_prepare_to_enter(v);
1471                         if (signal_pending(v->arch.run_task)) {
1472                                 kvmppc_remove_runnable(vc, v);
1473                                 v->stat.signal_exits++;
1474                                 v->arch.kvm_run->exit_reason = KVM_EXIT_INTR;
1475                                 v->arch.ret = -EINTR;
1476                                 wake_up(&v->arch.cpu_run);
1477                         }
1478                 }
1479                 if (!vc->n_runnable || vcpu->arch.state != KVMPPC_VCPU_RUNNABLE)
1480                         break;
1481                 vc->runner = vcpu;
1482                 n_ceded = 0;
1483                 list_for_each_entry(v, &vc->runnable_threads, arch.run_list) {
1484                         if (!v->arch.pending_exceptions)
1485                                 n_ceded += v->arch.ceded;
1486                         else
1487                                 v->arch.ceded = 0;
1488                 }
1489                 if (n_ceded == vc->n_runnable)
1490                         kvmppc_vcore_blocked(vc);
1491                 else
1492                         kvmppc_run_core(vc);
1493                 vc->runner = NULL;
1494         }
1495
1496         while (vcpu->arch.state == KVMPPC_VCPU_RUNNABLE &&
1497                (vc->vcore_state == VCORE_RUNNING ||
1498                 vc->vcore_state == VCORE_EXITING)) {
1499                 spin_unlock(&vc->lock);
1500                 kvmppc_wait_for_exec(vcpu, TASK_UNINTERRUPTIBLE);
1501                 spin_lock(&vc->lock);
1502         }
1503
1504         if (vcpu->arch.state == KVMPPC_VCPU_RUNNABLE) {
1505                 kvmppc_remove_runnable(vc, vcpu);
1506                 vcpu->stat.signal_exits++;
1507                 kvm_run->exit_reason = KVM_EXIT_INTR;
1508                 vcpu->arch.ret = -EINTR;
1509         }
1510
1511         if (vc->n_runnable && vc->vcore_state == VCORE_INACTIVE) {
1512                 /* Wake up some vcpu to run the core */
1513                 v = list_first_entry(&vc->runnable_threads,
1514                                      struct kvm_vcpu, arch.run_list);
1515                 wake_up(&v->arch.cpu_run);
1516         }
1517
1518         spin_unlock(&vc->lock);
1519         return vcpu->arch.ret;
1520 }
1521
1522 static int kvmppc_vcpu_run_hv(struct kvm_run *run, struct kvm_vcpu *vcpu)
1523 {
1524         int r;
1525         int srcu_idx;
1526
1527         if (!vcpu->arch.sane) {
1528                 run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
1529                 return -EINVAL;
1530         }
1531
1532         kvmppc_core_prepare_to_enter(vcpu);
1533
1534         /* No need to go into the guest when all we'll do is come back out */
1535         if (signal_pending(current)) {
1536                 run->exit_reason = KVM_EXIT_INTR;
1537                 return -EINTR;
1538         }
1539
1540         atomic_inc(&vcpu->kvm->arch.vcpus_running);
1541         /* Order vcpus_running vs. rma_setup_done, see kvmppc_alloc_reset_hpt */
1542         smp_mb();
1543
1544         /* On the first time here, set up HTAB and VRMA or RMA */
1545         if (!vcpu->kvm->arch.rma_setup_done) {
1546                 r = kvmppc_hv_setup_htab_rma(vcpu);
1547                 if (r)
1548                         goto out;
1549         }
1550
1551         flush_fp_to_thread(current);
1552         flush_altivec_to_thread(current);
1553         flush_vsx_to_thread(current);
1554         vcpu->arch.wqp = &vcpu->arch.vcore->wq;
1555         vcpu->arch.pgdir = current->mm->pgd;
1556         vcpu->arch.state = KVMPPC_VCPU_BUSY_IN_HOST;
1557
1558         do {
1559                 r = kvmppc_run_vcpu(run, vcpu);
1560
1561                 if (run->exit_reason == KVM_EXIT_PAPR_HCALL &&
1562                     !(vcpu->arch.shregs.msr & MSR_PR)) {
1563                         r = kvmppc_pseries_do_hcall(vcpu);
1564                         kvmppc_core_prepare_to_enter(vcpu);
1565                 } else if (r == RESUME_PAGE_FAULT) {
1566                         srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
1567                         r = kvmppc_book3s_hv_page_fault(run, vcpu,
1568                                 vcpu->arch.fault_dar, vcpu->arch.fault_dsisr);
1569                         srcu_read_unlock(&vcpu->kvm->srcu, srcu_idx);
1570                 }
1571         } while (r == RESUME_GUEST);
1572
1573  out:
1574         vcpu->arch.state = KVMPPC_VCPU_NOTREADY;
1575         atomic_dec(&vcpu->kvm->arch.vcpus_running);
1576         return r;
1577 }
1578
1579
1580 /* Work out RMLS (real mode limit selector) field value for a given RMA size.
1581    Assumes POWER7 or PPC970. */
1582 static inline int lpcr_rmls(unsigned long rma_size)
1583 {
1584         switch (rma_size) {
1585         case 32ul << 20:        /* 32 MB */
1586                 if (cpu_has_feature(CPU_FTR_ARCH_206))
1587                         return 8;       /* only supported on POWER7 */
1588                 return -1;
1589         case 64ul << 20:        /* 64 MB */
1590                 return 3;
1591         case 128ul << 20:       /* 128 MB */
1592                 return 7;
1593         case 256ul << 20:       /* 256 MB */
1594                 return 4;
1595         case 1ul << 30:         /* 1 GB */
1596                 return 2;
1597         case 16ul << 30:        /* 16 GB */
1598                 return 1;
1599         case 256ul << 30:       /* 256 GB */
1600                 return 0;
1601         default:
1602                 return -1;
1603         }
1604 }
1605
1606 static int kvm_rma_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
1607 {
1608         struct page *page;
1609         struct kvm_rma_info *ri = vma->vm_file->private_data;
1610
1611         if (vmf->pgoff >= kvm_rma_pages)
1612                 return VM_FAULT_SIGBUS;
1613
1614         page = pfn_to_page(ri->base_pfn + vmf->pgoff);
1615         get_page(page);
1616         vmf->page = page;
1617         return 0;
1618 }
1619
1620 static const struct vm_operations_struct kvm_rma_vm_ops = {
1621         .fault = kvm_rma_fault,
1622 };
1623
1624 static int kvm_rma_mmap(struct file *file, struct vm_area_struct *vma)
1625 {
1626         vma->vm_flags |= VM_DONTEXPAND | VM_DONTDUMP;
1627         vma->vm_ops = &kvm_rma_vm_ops;
1628         return 0;
1629 }
1630
1631 static int kvm_rma_release(struct inode *inode, struct file *filp)
1632 {
1633         struct kvm_rma_info *ri = filp->private_data;
1634
1635         kvm_release_rma(ri);
1636         return 0;
1637 }
1638
1639 static const struct file_operations kvm_rma_fops = {
1640         .mmap           = kvm_rma_mmap,
1641         .release        = kvm_rma_release,
1642 };
1643
1644 static long kvm_vm_ioctl_allocate_rma(struct kvm *kvm,
1645                                       struct kvm_allocate_rma *ret)
1646 {
1647         long fd;
1648         struct kvm_rma_info *ri;
1649         /*
1650          * Only do this on PPC970 in HV mode
1651          */
1652         if (!cpu_has_feature(CPU_FTR_HVMODE) ||
1653             !cpu_has_feature(CPU_FTR_ARCH_201))
1654                 return -EINVAL;
1655
1656         if (!kvm_rma_pages)
1657                 return -EINVAL;
1658
1659         ri = kvm_alloc_rma();
1660         if (!ri)
1661                 return -ENOMEM;
1662
1663         fd = anon_inode_getfd("kvm-rma", &kvm_rma_fops, ri, O_RDWR | O_CLOEXEC);
1664         if (fd < 0)
1665                 kvm_release_rma(ri);
1666
1667         ret->rma_size = kvm_rma_pages << PAGE_SHIFT;
1668         return fd;
1669 }
1670
1671 static void kvmppc_add_seg_page_size(struct kvm_ppc_one_seg_page_size **sps,
1672                                      int linux_psize)
1673 {
1674         struct mmu_psize_def *def = &mmu_psize_defs[linux_psize];
1675
1676         if (!def->shift)
1677                 return;
1678         (*sps)->page_shift = def->shift;
1679         (*sps)->slb_enc = def->sllp;
1680         (*sps)->enc[0].page_shift = def->shift;
1681         /*
1682          * Only return base page encoding. We don't want to return
1683          * all the supporting pte_enc, because our H_ENTER doesn't
1684          * support MPSS yet. Once they do, we can start passing all
1685          * support pte_enc here
1686          */
1687         (*sps)->enc[0].pte_enc = def->penc[linux_psize];
1688         (*sps)++;
1689 }
1690
1691 static int kvm_vm_ioctl_get_smmu_info_hv(struct kvm *kvm,
1692                                          struct kvm_ppc_smmu_info *info)
1693 {
1694         struct kvm_ppc_one_seg_page_size *sps;
1695
1696         info->flags = KVM_PPC_PAGE_SIZES_REAL;
1697         if (mmu_has_feature(MMU_FTR_1T_SEGMENT))
1698                 info->flags |= KVM_PPC_1T_SEGMENTS;
1699         info->slb_size = mmu_slb_size;
1700
1701         /* We only support these sizes for now, and no muti-size segments */
1702         sps = &info->sps[0];
1703         kvmppc_add_seg_page_size(&sps, MMU_PAGE_4K);
1704         kvmppc_add_seg_page_size(&sps, MMU_PAGE_64K);
1705         kvmppc_add_seg_page_size(&sps, MMU_PAGE_16M);
1706
1707         return 0;
1708 }
1709
1710 /*
1711  * Get (and clear) the dirty memory log for a memory slot.
1712  */
1713 static int kvm_vm_ioctl_get_dirty_log_hv(struct kvm *kvm,
1714                                          struct kvm_dirty_log *log)
1715 {
1716         struct kvm_memory_slot *memslot;
1717         int r;
1718         unsigned long n;
1719
1720         mutex_lock(&kvm->slots_lock);
1721
1722         r = -EINVAL;
1723         if (log->slot >= KVM_USER_MEM_SLOTS)
1724                 goto out;
1725
1726         memslot = id_to_memslot(kvm->memslots, log->slot);
1727         r = -ENOENT;
1728         if (!memslot->dirty_bitmap)
1729                 goto out;
1730
1731         n = kvm_dirty_bitmap_bytes(memslot);
1732         memset(memslot->dirty_bitmap, 0, n);
1733
1734         r = kvmppc_hv_get_dirty_log(kvm, memslot, memslot->dirty_bitmap);
1735         if (r)
1736                 goto out;
1737
1738         r = -EFAULT;
1739         if (copy_to_user(log->dirty_bitmap, memslot->dirty_bitmap, n))
1740                 goto out;
1741
1742         r = 0;
1743 out:
1744         mutex_unlock(&kvm->slots_lock);
1745         return r;
1746 }
1747
1748 static void unpin_slot(struct kvm_memory_slot *memslot)
1749 {
1750         unsigned long *physp;
1751         unsigned long j, npages, pfn;
1752         struct page *page;
1753
1754         physp = memslot->arch.slot_phys;
1755         npages = memslot->npages;
1756         if (!physp)
1757                 return;
1758         for (j = 0; j < npages; j++) {
1759                 if (!(physp[j] & KVMPPC_GOT_PAGE))
1760                         continue;
1761                 pfn = physp[j] >> PAGE_SHIFT;
1762                 page = pfn_to_page(pfn);
1763                 SetPageDirty(page);
1764                 put_page(page);
1765         }
1766 }
1767
1768 static void kvmppc_core_free_memslot_hv(struct kvm_memory_slot *free,
1769                                         struct kvm_memory_slot *dont)
1770 {
1771         if (!dont || free->arch.rmap != dont->arch.rmap) {
1772                 vfree(free->arch.rmap);
1773                 free->arch.rmap = NULL;
1774         }
1775         if (!dont || free->arch.slot_phys != dont->arch.slot_phys) {
1776                 unpin_slot(free);
1777                 vfree(free->arch.slot_phys);
1778                 free->arch.slot_phys = NULL;
1779         }
1780 }
1781
1782 static int kvmppc_core_create_memslot_hv(struct kvm_memory_slot *slot,
1783                                          unsigned long npages)
1784 {
1785         slot->arch.rmap = vzalloc(npages * sizeof(*slot->arch.rmap));
1786         if (!slot->arch.rmap)
1787                 return -ENOMEM;
1788         slot->arch.slot_phys = NULL;
1789
1790         return 0;
1791 }
1792
1793 static int kvmppc_core_prepare_memory_region_hv(struct kvm *kvm,
1794                                         struct kvm_memory_slot *memslot,
1795                                         struct kvm_userspace_memory_region *mem)
1796 {
1797         unsigned long *phys;
1798
1799         /* Allocate a slot_phys array if needed */
1800         phys = memslot->arch.slot_phys;
1801         if (!kvm->arch.using_mmu_notifiers && !phys && memslot->npages) {
1802                 phys = vzalloc(memslot->npages * sizeof(unsigned long));
1803                 if (!phys)
1804                         return -ENOMEM;
1805                 memslot->arch.slot_phys = phys;
1806         }
1807
1808         return 0;
1809 }
1810
1811 static void kvmppc_core_commit_memory_region_hv(struct kvm *kvm,
1812                                 struct kvm_userspace_memory_region *mem,
1813                                 const struct kvm_memory_slot *old)
1814 {
1815         unsigned long npages = mem->memory_size >> PAGE_SHIFT;
1816         struct kvm_memory_slot *memslot;
1817
1818         if (npages && old->npages) {
1819                 /*
1820                  * If modifying a memslot, reset all the rmap dirty bits.
1821                  * If this is a new memslot, we don't need to do anything
1822                  * since the rmap array starts out as all zeroes,
1823                  * i.e. no pages are dirty.
1824                  */
1825                 memslot = id_to_memslot(kvm->memslots, mem->slot);
1826                 kvmppc_hv_get_dirty_log(kvm, memslot, NULL);
1827         }
1828 }
1829
1830 /*
1831  * Update LPCR values in kvm->arch and in vcores.
1832  * Caller must hold kvm->lock.
1833  */
1834 void kvmppc_update_lpcr(struct kvm *kvm, unsigned long lpcr, unsigned long mask)
1835 {
1836         long int i;
1837         u32 cores_done = 0;
1838
1839         if ((kvm->arch.lpcr & mask) == lpcr)
1840                 return;
1841
1842         kvm->arch.lpcr = (kvm->arch.lpcr & ~mask) | lpcr;
1843
1844         for (i = 0; i < KVM_MAX_VCORES; ++i) {
1845                 struct kvmppc_vcore *vc = kvm->arch.vcores[i];
1846                 if (!vc)
1847                         continue;
1848                 spin_lock(&vc->lock);
1849                 vc->lpcr = (vc->lpcr & ~mask) | lpcr;
1850                 spin_unlock(&vc->lock);
1851                 if (++cores_done >= kvm->arch.online_vcores)
1852                         break;
1853         }
1854 }
1855
1856 static void kvmppc_mmu_destroy_hv(struct kvm_vcpu *vcpu)
1857 {
1858         return;
1859 }
1860
1861 static int kvmppc_hv_setup_htab_rma(struct kvm_vcpu *vcpu)
1862 {
1863         int err = 0;
1864         struct kvm *kvm = vcpu->kvm;
1865         struct kvm_rma_info *ri = NULL;
1866         unsigned long hva;
1867         struct kvm_memory_slot *memslot;
1868         struct vm_area_struct *vma;
1869         unsigned long lpcr = 0, senc;
1870         unsigned long lpcr_mask = 0;
1871         unsigned long psize, porder;
1872         unsigned long rma_size;
1873         unsigned long rmls;
1874         unsigned long *physp;
1875         unsigned long i, npages;
1876         int srcu_idx;
1877
1878         mutex_lock(&kvm->lock);
1879         if (kvm->arch.rma_setup_done)
1880                 goto out;       /* another vcpu beat us to it */
1881
1882         /* Allocate hashed page table (if not done already) and reset it */
1883         if (!kvm->arch.hpt_virt) {
1884                 err = kvmppc_alloc_hpt(kvm, NULL);
1885                 if (err) {
1886                         pr_err("KVM: Couldn't alloc HPT\n");
1887                         goto out;
1888                 }
1889         }
1890
1891         /* Look up the memslot for guest physical address 0 */
1892         srcu_idx = srcu_read_lock(&kvm->srcu);
1893         memslot = gfn_to_memslot(kvm, 0);
1894
1895         /* We must have some memory at 0 by now */
1896         err = -EINVAL;
1897         if (!memslot || (memslot->flags & KVM_MEMSLOT_INVALID))
1898                 goto out_srcu;
1899
1900         /* Look up the VMA for the start of this memory slot */
1901         hva = memslot->userspace_addr;
1902         down_read(&current->mm->mmap_sem);
1903         vma = find_vma(current->mm, hva);
1904         if (!vma || vma->vm_start > hva || (vma->vm_flags & VM_IO))
1905                 goto up_out;
1906
1907         psize = vma_kernel_pagesize(vma);
1908         porder = __ilog2(psize);
1909
1910         /* Is this one of our preallocated RMAs? */
1911         if (vma->vm_file && vma->vm_file->f_op == &kvm_rma_fops &&
1912             hva == vma->vm_start)
1913                 ri = vma->vm_file->private_data;
1914
1915         up_read(&current->mm->mmap_sem);
1916
1917         if (!ri) {
1918                 /* On POWER7, use VRMA; on PPC970, give up */
1919                 err = -EPERM;
1920                 if (cpu_has_feature(CPU_FTR_ARCH_201)) {
1921                         pr_err("KVM: CPU requires an RMO\n");
1922                         goto out_srcu;
1923                 }
1924
1925                 /* We can handle 4k, 64k or 16M pages in the VRMA */
1926                 err = -EINVAL;
1927                 if (!(psize == 0x1000 || psize == 0x10000 ||
1928                       psize == 0x1000000))
1929                         goto out_srcu;
1930
1931                 /* Update VRMASD field in the LPCR */
1932                 senc = slb_pgsize_encoding(psize);
1933                 kvm->arch.vrma_slb_v = senc | SLB_VSID_B_1T |
1934                         (VRMA_VSID << SLB_VSID_SHIFT_1T);
1935                 lpcr_mask = LPCR_VRMASD;
1936                 /* the -4 is to account for senc values starting at 0x10 */
1937                 lpcr = senc << (LPCR_VRMASD_SH - 4);
1938
1939                 /* Create HPTEs in the hash page table for the VRMA */
1940                 kvmppc_map_vrma(vcpu, memslot, porder);
1941
1942         } else {
1943                 /* Set up to use an RMO region */
1944                 rma_size = kvm_rma_pages;
1945                 if (rma_size > memslot->npages)
1946                         rma_size = memslot->npages;
1947                 rma_size <<= PAGE_SHIFT;
1948                 rmls = lpcr_rmls(rma_size);
1949                 err = -EINVAL;
1950                 if ((long)rmls < 0) {
1951                         pr_err("KVM: Can't use RMA of 0x%lx bytes\n", rma_size);
1952                         goto out_srcu;
1953                 }
1954                 atomic_inc(&ri->use_count);
1955                 kvm->arch.rma = ri;
1956
1957                 /* Update LPCR and RMOR */
1958                 if (cpu_has_feature(CPU_FTR_ARCH_201)) {
1959                         /* PPC970; insert RMLS value (split field) in HID4 */
1960                         lpcr_mask = (1ul << HID4_RMLS0_SH) |
1961                                 (3ul << HID4_RMLS2_SH) | HID4_RMOR;
1962                         lpcr = ((rmls >> 2) << HID4_RMLS0_SH) |
1963                                 ((rmls & 3) << HID4_RMLS2_SH);
1964                         /* RMOR is also in HID4 */
1965                         lpcr |= ((ri->base_pfn >> (26 - PAGE_SHIFT)) & 0xffff)
1966                                 << HID4_RMOR_SH;
1967                 } else {
1968                         /* POWER7 */
1969                         lpcr_mask = LPCR_VPM0 | LPCR_VRMA_L | LPCR_RMLS;
1970                         lpcr = rmls << LPCR_RMLS_SH;
1971                         kvm->arch.rmor = ri->base_pfn << PAGE_SHIFT;
1972                 }
1973                 pr_info("KVM: Using RMO at %lx size %lx (LPCR = %lx)\n",
1974                         ri->base_pfn << PAGE_SHIFT, rma_size, lpcr);
1975
1976                 /* Initialize phys addrs of pages in RMO */
1977                 npages = kvm_rma_pages;
1978                 porder = __ilog2(npages);
1979                 physp = memslot->arch.slot_phys;
1980                 if (physp) {
1981                         if (npages > memslot->npages)
1982                                 npages = memslot->npages;
1983                         spin_lock(&kvm->arch.slot_phys_lock);
1984                         for (i = 0; i < npages; ++i)
1985                                 physp[i] = ((ri->base_pfn + i) << PAGE_SHIFT) +
1986                                         porder;
1987                         spin_unlock(&kvm->arch.slot_phys_lock);
1988                 }
1989         }
1990
1991         kvmppc_update_lpcr(kvm, lpcr, lpcr_mask);
1992
1993         /* Order updates to kvm->arch.lpcr etc. vs. rma_setup_done */
1994         smp_wmb();
1995         kvm->arch.rma_setup_done = 1;
1996         err = 0;
1997  out_srcu:
1998         srcu_read_unlock(&kvm->srcu, srcu_idx);
1999  out:
2000         mutex_unlock(&kvm->lock);
2001         return err;
2002
2003  up_out:
2004         up_read(&current->mm->mmap_sem);
2005         goto out_srcu;
2006 }
2007
2008 static int kvmppc_core_init_vm_hv(struct kvm *kvm)
2009 {
2010         unsigned long lpcr, lpid;
2011
2012         /* Allocate the guest's logical partition ID */
2013
2014         lpid = kvmppc_alloc_lpid();
2015         if ((long)lpid < 0)
2016                 return -ENOMEM;
2017         kvm->arch.lpid = lpid;
2018
2019         /*
2020          * Since we don't flush the TLB when tearing down a VM,
2021          * and this lpid might have previously been used,
2022          * make sure we flush on each core before running the new VM.
2023          */
2024         cpumask_setall(&kvm->arch.need_tlb_flush);
2025
2026         kvm->arch.rma = NULL;
2027
2028         kvm->arch.host_sdr1 = mfspr(SPRN_SDR1);
2029
2030         if (cpu_has_feature(CPU_FTR_ARCH_201)) {
2031                 /* PPC970; HID4 is effectively the LPCR */
2032                 kvm->arch.host_lpid = 0;
2033                 kvm->arch.host_lpcr = lpcr = mfspr(SPRN_HID4);
2034                 lpcr &= ~((3 << HID4_LPID1_SH) | (0xful << HID4_LPID5_SH));
2035                 lpcr |= ((lpid >> 4) << HID4_LPID1_SH) |
2036                         ((lpid & 0xf) << HID4_LPID5_SH);
2037         } else {
2038                 /* POWER7; init LPCR for virtual RMA mode */
2039                 kvm->arch.host_lpid = mfspr(SPRN_LPID);
2040                 kvm->arch.host_lpcr = lpcr = mfspr(SPRN_LPCR);
2041                 lpcr &= LPCR_PECE | LPCR_LPES;
2042                 lpcr |= (4UL << LPCR_DPFD_SH) | LPCR_HDICE |
2043                         LPCR_VPM0 | LPCR_VPM1;
2044                 kvm->arch.vrma_slb_v = SLB_VSID_B_1T |
2045                         (VRMA_VSID << SLB_VSID_SHIFT_1T);
2046         }
2047         kvm->arch.lpcr = lpcr;
2048
2049         kvm->arch.using_mmu_notifiers = !!cpu_has_feature(CPU_FTR_ARCH_206);
2050         spin_lock_init(&kvm->arch.slot_phys_lock);
2051
2052         /*
2053          * Don't allow secondary CPU threads to come online
2054          * while any KVM VMs exist.
2055          */
2056         inhibit_secondary_onlining();
2057
2058         return 0;
2059 }
2060
2061 static void kvmppc_free_vcores(struct kvm *kvm)
2062 {
2063         long int i;
2064
2065         for (i = 0; i < KVM_MAX_VCORES; ++i)
2066                 kfree(kvm->arch.vcores[i]);
2067         kvm->arch.online_vcores = 0;
2068 }
2069
2070 static void kvmppc_core_destroy_vm_hv(struct kvm *kvm)
2071 {
2072         uninhibit_secondary_onlining();
2073
2074         kvmppc_free_vcores(kvm);
2075         if (kvm->arch.rma) {
2076                 kvm_release_rma(kvm->arch.rma);
2077                 kvm->arch.rma = NULL;
2078         }
2079
2080         kvmppc_free_hpt(kvm);
2081 }
2082
2083 /* We don't need to emulate any privileged instructions or dcbz */
2084 static int kvmppc_core_emulate_op_hv(struct kvm_run *run, struct kvm_vcpu *vcpu,
2085                                      unsigned int inst, int *advance)
2086 {
2087         return EMULATE_FAIL;
2088 }
2089
2090 static int kvmppc_core_emulate_mtspr_hv(struct kvm_vcpu *vcpu, int sprn,
2091                                         ulong spr_val)
2092 {
2093         return EMULATE_FAIL;
2094 }
2095
2096 static int kvmppc_core_emulate_mfspr_hv(struct kvm_vcpu *vcpu, int sprn,
2097                                         ulong *spr_val)
2098 {
2099         return EMULATE_FAIL;
2100 }
2101
2102 static int kvmppc_core_check_processor_compat_hv(void)
2103 {
2104         if (!cpu_has_feature(CPU_FTR_HVMODE))
2105                 return -EIO;
2106         return 0;
2107 }
2108
2109 static long kvm_arch_vm_ioctl_hv(struct file *filp,
2110                                  unsigned int ioctl, unsigned long arg)
2111 {
2112         struct kvm *kvm __maybe_unused = filp->private_data;
2113         void __user *argp = (void __user *)arg;
2114         long r;
2115
2116         switch (ioctl) {
2117
2118         case KVM_ALLOCATE_RMA: {
2119                 struct kvm_allocate_rma rma;
2120                 struct kvm *kvm = filp->private_data;
2121
2122                 r = kvm_vm_ioctl_allocate_rma(kvm, &rma);
2123                 if (r >= 0 && copy_to_user(argp, &rma, sizeof(rma)))
2124                         r = -EFAULT;
2125                 break;
2126         }
2127
2128         case KVM_PPC_ALLOCATE_HTAB: {
2129                 u32 htab_order;
2130
2131                 r = -EFAULT;
2132                 if (get_user(htab_order, (u32 __user *)argp))
2133                         break;
2134                 r = kvmppc_alloc_reset_hpt(kvm, &htab_order);
2135                 if (r)
2136                         break;
2137                 r = -EFAULT;
2138                 if (put_user(htab_order, (u32 __user *)argp))
2139                         break;
2140                 r = 0;
2141                 break;
2142         }
2143
2144         case KVM_PPC_GET_HTAB_FD: {
2145                 struct kvm_get_htab_fd ghf;
2146
2147                 r = -EFAULT;
2148                 if (copy_from_user(&ghf, argp, sizeof(ghf)))
2149                         break;
2150                 r = kvm_vm_ioctl_get_htab_fd(kvm, &ghf);
2151                 break;
2152         }
2153
2154         default:
2155                 r = -ENOTTY;
2156         }
2157
2158         return r;
2159 }
2160
2161 static struct kvmppc_ops kvmppc_hv_ops = {
2162         .is_hv_enabled = true,
2163         .get_sregs = kvm_arch_vcpu_ioctl_get_sregs_hv,
2164         .set_sregs = kvm_arch_vcpu_ioctl_set_sregs_hv,
2165         .get_one_reg = kvmppc_get_one_reg_hv,
2166         .set_one_reg = kvmppc_set_one_reg_hv,
2167         .vcpu_load   = kvmppc_core_vcpu_load_hv,
2168         .vcpu_put    = kvmppc_core_vcpu_put_hv,
2169         .set_msr     = kvmppc_set_msr_hv,
2170         .vcpu_run    = kvmppc_vcpu_run_hv,
2171         .vcpu_create = kvmppc_core_vcpu_create_hv,
2172         .vcpu_free   = kvmppc_core_vcpu_free_hv,
2173         .check_requests = kvmppc_core_check_requests_hv,
2174         .get_dirty_log  = kvm_vm_ioctl_get_dirty_log_hv,
2175         .flush_memslot  = kvmppc_core_flush_memslot_hv,
2176         .prepare_memory_region = kvmppc_core_prepare_memory_region_hv,
2177         .commit_memory_region  = kvmppc_core_commit_memory_region_hv,
2178         .unmap_hva = kvm_unmap_hva_hv,
2179         .unmap_hva_range = kvm_unmap_hva_range_hv,
2180         .age_hva  = kvm_age_hva_hv,
2181         .test_age_hva = kvm_test_age_hva_hv,
2182         .set_spte_hva = kvm_set_spte_hva_hv,
2183         .mmu_destroy  = kvmppc_mmu_destroy_hv,
2184         .free_memslot = kvmppc_core_free_memslot_hv,
2185         .create_memslot = kvmppc_core_create_memslot_hv,
2186         .init_vm =  kvmppc_core_init_vm_hv,
2187         .destroy_vm = kvmppc_core_destroy_vm_hv,
2188         .check_processor_compat = kvmppc_core_check_processor_compat_hv,
2189         .get_smmu_info = kvm_vm_ioctl_get_smmu_info_hv,
2190         .emulate_op = kvmppc_core_emulate_op_hv,
2191         .emulate_mtspr = kvmppc_core_emulate_mtspr_hv,
2192         .emulate_mfspr = kvmppc_core_emulate_mfspr_hv,
2193         .fast_vcpu_kick = kvmppc_fast_vcpu_kick_hv,
2194         .arch_vm_ioctl  = kvm_arch_vm_ioctl_hv,
2195 };
2196
2197 static int kvmppc_book3s_init_hv(void)
2198 {
2199         int r;
2200
2201         r = kvm_init(&kvmppc_hv_ops, sizeof(struct kvm_vcpu), 0, THIS_MODULE);
2202
2203         if (r)
2204                 return r;
2205
2206         r = kvmppc_mmu_hv_init();
2207
2208         return r;
2209 }
2210
2211 static void kvmppc_book3s_exit_hv(void)
2212 {
2213         kvm_exit();
2214 }
2215
2216 module_init(kvmppc_book3s_init_hv);
2217 module_exit(kvmppc_book3s_exit_hv);