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