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