KVM: PPC: Book3S HV: Make virtual processor area registration more robust
[firefly-linux-kernel-4.4.55.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
34 #include <asm/reg.h>
35 #include <asm/cputable.h>
36 #include <asm/cacheflush.h>
37 #include <asm/tlbflush.h>
38 #include <asm/uaccess.h>
39 #include <asm/io.h>
40 #include <asm/kvm_ppc.h>
41 #include <asm/kvm_book3s.h>
42 #include <asm/mmu_context.h>
43 #include <asm/lppaca.h>
44 #include <asm/processor.h>
45 #include <asm/cputhreads.h>
46 #include <asm/page.h>
47 #include <asm/hvcall.h>
48 #include <asm/switch_to.h>
49 #include <linux/gfp.h>
50 #include <linux/vmalloc.h>
51 #include <linux/highmem.h>
52 #include <linux/hugetlb.h>
53
54 /* #define EXIT_DEBUG */
55 /* #define EXIT_DEBUG_SIMPLE */
56 /* #define EXIT_DEBUG_INT */
57
58 static void kvmppc_end_cede(struct kvm_vcpu *vcpu);
59 static int kvmppc_hv_setup_rma(struct kvm_vcpu *vcpu);
60
61 void kvmppc_core_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
62 {
63         local_paca->kvm_hstate.kvm_vcpu = vcpu;
64         local_paca->kvm_hstate.kvm_vcore = vcpu->arch.vcore;
65 }
66
67 void kvmppc_core_vcpu_put(struct kvm_vcpu *vcpu)
68 {
69 }
70
71 void kvmppc_set_msr(struct kvm_vcpu *vcpu, u64 msr)
72 {
73         vcpu->arch.shregs.msr = msr;
74         kvmppc_end_cede(vcpu);
75 }
76
77 void kvmppc_set_pvr(struct kvm_vcpu *vcpu, u32 pvr)
78 {
79         vcpu->arch.pvr = pvr;
80 }
81
82 void kvmppc_dump_regs(struct kvm_vcpu *vcpu)
83 {
84         int r;
85
86         pr_err("vcpu %p (%d):\n", vcpu, vcpu->vcpu_id);
87         pr_err("pc  = %.16lx  msr = %.16llx  trap = %x\n",
88                vcpu->arch.pc, vcpu->arch.shregs.msr, vcpu->arch.trap);
89         for (r = 0; r < 16; ++r)
90                 pr_err("r%2d = %.16lx  r%d = %.16lx\n",
91                        r, kvmppc_get_gpr(vcpu, r),
92                        r+16, kvmppc_get_gpr(vcpu, r+16));
93         pr_err("ctr = %.16lx  lr  = %.16lx\n",
94                vcpu->arch.ctr, vcpu->arch.lr);
95         pr_err("srr0 = %.16llx srr1 = %.16llx\n",
96                vcpu->arch.shregs.srr0, vcpu->arch.shregs.srr1);
97         pr_err("sprg0 = %.16llx sprg1 = %.16llx\n",
98                vcpu->arch.shregs.sprg0, vcpu->arch.shregs.sprg1);
99         pr_err("sprg2 = %.16llx sprg3 = %.16llx\n",
100                vcpu->arch.shregs.sprg2, vcpu->arch.shregs.sprg3);
101         pr_err("cr = %.8x  xer = %.16lx  dsisr = %.8x\n",
102                vcpu->arch.cr, vcpu->arch.xer, vcpu->arch.shregs.dsisr);
103         pr_err("dar = %.16llx\n", vcpu->arch.shregs.dar);
104         pr_err("fault dar = %.16lx dsisr = %.8x\n",
105                vcpu->arch.fault_dar, vcpu->arch.fault_dsisr);
106         pr_err("SLB (%d entries):\n", vcpu->arch.slb_max);
107         for (r = 0; r < vcpu->arch.slb_max; ++r)
108                 pr_err("  ESID = %.16llx VSID = %.16llx\n",
109                        vcpu->arch.slb[r].orige, vcpu->arch.slb[r].origv);
110         pr_err("lpcr = %.16lx sdr1 = %.16lx last_inst = %.8x\n",
111                vcpu->kvm->arch.lpcr, vcpu->kvm->arch.sdr1,
112                vcpu->arch.last_inst);
113 }
114
115 struct kvm_vcpu *kvmppc_find_vcpu(struct kvm *kvm, int id)
116 {
117         int r;
118         struct kvm_vcpu *v, *ret = NULL;
119
120         mutex_lock(&kvm->lock);
121         kvm_for_each_vcpu(r, v, kvm) {
122                 if (v->vcpu_id == id) {
123                         ret = v;
124                         break;
125                 }
126         }
127         mutex_unlock(&kvm->lock);
128         return ret;
129 }
130
131 static void init_vpa(struct kvm_vcpu *vcpu, struct lppaca *vpa)
132 {
133         vpa->shared_proc = 1;
134         vpa->yield_count = 1;
135 }
136
137 /* Length for a per-processor buffer is passed in at offset 4 in the buffer */
138 struct reg_vpa {
139         u32 dummy;
140         union {
141                 u16 hword;
142                 u32 word;
143         } length;
144 };
145
146 static int vpa_is_registered(struct kvmppc_vpa *vpap)
147 {
148         if (vpap->update_pending)
149                 return vpap->next_gpa != 0;
150         return vpap->pinned_addr != NULL;
151 }
152
153 static unsigned long do_h_register_vpa(struct kvm_vcpu *vcpu,
154                                        unsigned long flags,
155                                        unsigned long vcpuid, unsigned long vpa)
156 {
157         struct kvm *kvm = vcpu->kvm;
158         unsigned long len, nb;
159         void *va;
160         struct kvm_vcpu *tvcpu;
161         int err;
162         int subfunc;
163         struct kvmppc_vpa *vpap;
164
165         tvcpu = kvmppc_find_vcpu(kvm, vcpuid);
166         if (!tvcpu)
167                 return H_PARAMETER;
168
169         subfunc = (flags >> H_VPA_FUNC_SHIFT) & H_VPA_FUNC_MASK;
170         if (subfunc == H_VPA_REG_VPA || subfunc == H_VPA_REG_DTL ||
171             subfunc == H_VPA_REG_SLB) {
172                 /* Registering new area - address must be cache-line aligned */
173                 if ((vpa & (L1_CACHE_BYTES - 1)) || !vpa)
174                         return H_PARAMETER;
175
176                 /* convert logical addr to kernel addr and read length */
177                 va = kvmppc_pin_guest_page(kvm, vpa, &nb);
178                 if (va == NULL)
179                         return H_PARAMETER;
180                 if (subfunc == H_VPA_REG_VPA)
181                         len = ((struct reg_vpa *)va)->length.hword;
182                 else
183                         len = ((struct reg_vpa *)va)->length.word;
184                 kvmppc_unpin_guest_page(kvm, va);
185
186                 /* Check length */
187                 if (len > nb || len < sizeof(struct reg_vpa))
188                         return H_PARAMETER;
189         } else {
190                 vpa = 0;
191                 len = 0;
192         }
193
194         err = H_PARAMETER;
195         vpap = NULL;
196         spin_lock(&tvcpu->arch.vpa_update_lock);
197
198         switch (subfunc) {
199         case H_VPA_REG_VPA:             /* register VPA */
200                 if (len < sizeof(struct lppaca))
201                         break;
202                 vpap = &tvcpu->arch.vpa;
203                 err = 0;
204                 break;
205
206         case H_VPA_REG_DTL:             /* register DTL */
207                 if (len < sizeof(struct dtl_entry))
208                         break;
209                 len -= len % sizeof(struct dtl_entry);
210
211                 /* Check that they have previously registered a VPA */
212                 err = H_RESOURCE;
213                 if (!vpa_is_registered(&tvcpu->arch.vpa))
214                         break;
215
216                 vpap = &tvcpu->arch.dtl;
217                 err = 0;
218                 break;
219
220         case H_VPA_REG_SLB:             /* register SLB shadow buffer */
221                 /* Check that they have previously registered a VPA */
222                 err = H_RESOURCE;
223                 if (!vpa_is_registered(&tvcpu->arch.vpa))
224                         break;
225
226                 vpap = &tvcpu->arch.slb_shadow;
227                 err = 0;
228                 break;
229
230         case H_VPA_DEREG_VPA:           /* deregister VPA */
231                 /* Check they don't still have a DTL or SLB buf registered */
232                 err = H_RESOURCE;
233                 if (vpa_is_registered(&tvcpu->arch.dtl) ||
234                     vpa_is_registered(&tvcpu->arch.slb_shadow))
235                         break;
236
237                 vpap = &tvcpu->arch.vpa;
238                 err = 0;
239                 break;
240
241         case H_VPA_DEREG_DTL:           /* deregister DTL */
242                 vpap = &tvcpu->arch.dtl;
243                 err = 0;
244                 break;
245
246         case H_VPA_DEREG_SLB:           /* deregister SLB shadow buffer */
247                 vpap = &tvcpu->arch.slb_shadow;
248                 err = 0;
249                 break;
250         }
251
252         if (vpap) {
253                 vpap->next_gpa = vpa;
254                 vpap->len = len;
255                 vpap->update_pending = 1;
256         }
257
258         spin_unlock(&tvcpu->arch.vpa_update_lock);
259
260         return err;
261 }
262
263 static void kvmppc_update_vpa(struct kvm *kvm, struct kvmppc_vpa *vpap)
264 {
265         void *va;
266         unsigned long nb;
267
268         vpap->update_pending = 0;
269         va = NULL;
270         if (vpap->next_gpa) {
271                 va = kvmppc_pin_guest_page(kvm, vpap->next_gpa, &nb);
272                 if (nb < vpap->len) {
273                         /*
274                          * If it's now too short, it must be that userspace
275                          * has changed the mappings underlying guest memory,
276                          * so unregister the region.
277                          */
278                         kvmppc_unpin_guest_page(kvm, va);
279                         va = NULL;
280                 }
281         }
282         if (vpap->pinned_addr)
283                 kvmppc_unpin_guest_page(kvm, vpap->pinned_addr);
284         vpap->pinned_addr = va;
285         if (va)
286                 vpap->pinned_end = va + vpap->len;
287 }
288
289 static void kvmppc_update_vpas(struct kvm_vcpu *vcpu)
290 {
291         struct kvm *kvm = vcpu->kvm;
292
293         spin_lock(&vcpu->arch.vpa_update_lock);
294         if (vcpu->arch.vpa.update_pending) {
295                 kvmppc_update_vpa(kvm, &vcpu->arch.vpa);
296                 init_vpa(vcpu, vcpu->arch.vpa.pinned_addr);
297         }
298         if (vcpu->arch.dtl.update_pending) {
299                 kvmppc_update_vpa(kvm, &vcpu->arch.dtl);
300                 vcpu->arch.dtl_ptr = vcpu->arch.dtl.pinned_addr;
301                 vcpu->arch.dtl_index = 0;
302         }
303         if (vcpu->arch.slb_shadow.update_pending)
304                 kvmppc_update_vpa(kvm, &vcpu->arch.slb_shadow);
305         spin_unlock(&vcpu->arch.vpa_update_lock);
306 }
307
308 int kvmppc_pseries_do_hcall(struct kvm_vcpu *vcpu)
309 {
310         unsigned long req = kvmppc_get_gpr(vcpu, 3);
311         unsigned long target, ret = H_SUCCESS;
312         struct kvm_vcpu *tvcpu;
313
314         switch (req) {
315         case H_ENTER:
316                 ret = kvmppc_virtmode_h_enter(vcpu, kvmppc_get_gpr(vcpu, 4),
317                                               kvmppc_get_gpr(vcpu, 5),
318                                               kvmppc_get_gpr(vcpu, 6),
319                                               kvmppc_get_gpr(vcpu, 7));
320                 break;
321         case H_CEDE:
322                 break;
323         case H_PROD:
324                 target = kvmppc_get_gpr(vcpu, 4);
325                 tvcpu = kvmppc_find_vcpu(vcpu->kvm, target);
326                 if (!tvcpu) {
327                         ret = H_PARAMETER;
328                         break;
329                 }
330                 tvcpu->arch.prodded = 1;
331                 smp_mb();
332                 if (vcpu->arch.ceded) {
333                         if (waitqueue_active(&vcpu->wq)) {
334                                 wake_up_interruptible(&vcpu->wq);
335                                 vcpu->stat.halt_wakeup++;
336                         }
337                 }
338                 break;
339         case H_CONFER:
340                 break;
341         case H_REGISTER_VPA:
342                 ret = do_h_register_vpa(vcpu, kvmppc_get_gpr(vcpu, 4),
343                                         kvmppc_get_gpr(vcpu, 5),
344                                         kvmppc_get_gpr(vcpu, 6));
345                 break;
346         default:
347                 return RESUME_HOST;
348         }
349         kvmppc_set_gpr(vcpu, 3, ret);
350         vcpu->arch.hcall_needed = 0;
351         return RESUME_GUEST;
352 }
353
354 static int kvmppc_handle_exit(struct kvm_run *run, struct kvm_vcpu *vcpu,
355                               struct task_struct *tsk)
356 {
357         int r = RESUME_HOST;
358
359         vcpu->stat.sum_exits++;
360
361         run->exit_reason = KVM_EXIT_UNKNOWN;
362         run->ready_for_interrupt_injection = 1;
363         switch (vcpu->arch.trap) {
364         /* We're good on these - the host merely wanted to get our attention */
365         case BOOK3S_INTERRUPT_HV_DECREMENTER:
366                 vcpu->stat.dec_exits++;
367                 r = RESUME_GUEST;
368                 break;
369         case BOOK3S_INTERRUPT_EXTERNAL:
370                 vcpu->stat.ext_intr_exits++;
371                 r = RESUME_GUEST;
372                 break;
373         case BOOK3S_INTERRUPT_PERFMON:
374                 r = RESUME_GUEST;
375                 break;
376         case BOOK3S_INTERRUPT_PROGRAM:
377         {
378                 ulong flags;
379                 /*
380                  * Normally program interrupts are delivered directly
381                  * to the guest by the hardware, but we can get here
382                  * as a result of a hypervisor emulation interrupt
383                  * (e40) getting turned into a 700 by BML RTAS.
384                  */
385                 flags = vcpu->arch.shregs.msr & 0x1f0000ull;
386                 kvmppc_core_queue_program(vcpu, flags);
387                 r = RESUME_GUEST;
388                 break;
389         }
390         case BOOK3S_INTERRUPT_SYSCALL:
391         {
392                 /* hcall - punt to userspace */
393                 int i;
394
395                 if (vcpu->arch.shregs.msr & MSR_PR) {
396                         /* sc 1 from userspace - reflect to guest syscall */
397                         kvmppc_book3s_queue_irqprio(vcpu, BOOK3S_INTERRUPT_SYSCALL);
398                         r = RESUME_GUEST;
399                         break;
400                 }
401                 run->papr_hcall.nr = kvmppc_get_gpr(vcpu, 3);
402                 for (i = 0; i < 9; ++i)
403                         run->papr_hcall.args[i] = kvmppc_get_gpr(vcpu, 4 + i);
404                 run->exit_reason = KVM_EXIT_PAPR_HCALL;
405                 vcpu->arch.hcall_needed = 1;
406                 r = RESUME_HOST;
407                 break;
408         }
409         /*
410          * We get these next two if the guest accesses a page which it thinks
411          * it has mapped but which is not actually present, either because
412          * it is for an emulated I/O device or because the corresonding
413          * host page has been paged out.  Any other HDSI/HISI interrupts
414          * have been handled already.
415          */
416         case BOOK3S_INTERRUPT_H_DATA_STORAGE:
417                 r = kvmppc_book3s_hv_page_fault(run, vcpu,
418                                 vcpu->arch.fault_dar, vcpu->arch.fault_dsisr);
419                 break;
420         case BOOK3S_INTERRUPT_H_INST_STORAGE:
421                 r = kvmppc_book3s_hv_page_fault(run, vcpu,
422                                 kvmppc_get_pc(vcpu), 0);
423                 break;
424         /*
425          * This occurs if the guest executes an illegal instruction.
426          * We just generate a program interrupt to the guest, since
427          * we don't emulate any guest instructions at this stage.
428          */
429         case BOOK3S_INTERRUPT_H_EMUL_ASSIST:
430                 kvmppc_core_queue_program(vcpu, 0x80000);
431                 r = RESUME_GUEST;
432                 break;
433         default:
434                 kvmppc_dump_regs(vcpu);
435                 printk(KERN_EMERG "trap=0x%x | pc=0x%lx | msr=0x%llx\n",
436                         vcpu->arch.trap, kvmppc_get_pc(vcpu),
437                         vcpu->arch.shregs.msr);
438                 r = RESUME_HOST;
439                 BUG();
440                 break;
441         }
442
443         return r;
444 }
445
446 int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
447                                   struct kvm_sregs *sregs)
448 {
449         int i;
450
451         sregs->pvr = vcpu->arch.pvr;
452
453         memset(sregs, 0, sizeof(struct kvm_sregs));
454         for (i = 0; i < vcpu->arch.slb_max; i++) {
455                 sregs->u.s.ppc64.slb[i].slbe = vcpu->arch.slb[i].orige;
456                 sregs->u.s.ppc64.slb[i].slbv = vcpu->arch.slb[i].origv;
457         }
458
459         return 0;
460 }
461
462 int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
463                                   struct kvm_sregs *sregs)
464 {
465         int i, j;
466
467         kvmppc_set_pvr(vcpu, sregs->pvr);
468
469         j = 0;
470         for (i = 0; i < vcpu->arch.slb_nr; i++) {
471                 if (sregs->u.s.ppc64.slb[i].slbe & SLB_ESID_V) {
472                         vcpu->arch.slb[j].orige = sregs->u.s.ppc64.slb[i].slbe;
473                         vcpu->arch.slb[j].origv = sregs->u.s.ppc64.slb[i].slbv;
474                         ++j;
475                 }
476         }
477         vcpu->arch.slb_max = j;
478
479         return 0;
480 }
481
482 int kvm_vcpu_ioctl_get_one_reg(struct kvm_vcpu *vcpu, struct kvm_one_reg *reg)
483 {
484         int r = -EINVAL;
485
486         switch (reg->id) {
487         case KVM_REG_PPC_HIOR:
488                 r = put_user(0, (u64 __user *)reg->addr);
489                 break;
490         default:
491                 break;
492         }
493
494         return r;
495 }
496
497 int kvm_vcpu_ioctl_set_one_reg(struct kvm_vcpu *vcpu, struct kvm_one_reg *reg)
498 {
499         int r = -EINVAL;
500
501         switch (reg->id) {
502         case KVM_REG_PPC_HIOR:
503         {
504                 u64 hior;
505                 /* Only allow this to be set to zero */
506                 r = get_user(hior, (u64 __user *)reg->addr);
507                 if (!r && (hior != 0))
508                         r = -EINVAL;
509                 break;
510         }
511         default:
512                 break;
513         }
514
515         return r;
516 }
517
518 int kvmppc_core_check_processor_compat(void)
519 {
520         if (cpu_has_feature(CPU_FTR_HVMODE))
521                 return 0;
522         return -EIO;
523 }
524
525 struct kvm_vcpu *kvmppc_core_vcpu_create(struct kvm *kvm, unsigned int id)
526 {
527         struct kvm_vcpu *vcpu;
528         int err = -EINVAL;
529         int core;
530         struct kvmppc_vcore *vcore;
531
532         core = id / threads_per_core;
533         if (core >= KVM_MAX_VCORES)
534                 goto out;
535
536         err = -ENOMEM;
537         vcpu = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL);
538         if (!vcpu)
539                 goto out;
540
541         err = kvm_vcpu_init(vcpu, kvm, id);
542         if (err)
543                 goto free_vcpu;
544
545         vcpu->arch.shared = &vcpu->arch.shregs;
546         vcpu->arch.last_cpu = -1;
547         vcpu->arch.mmcr[0] = MMCR0_FC;
548         vcpu->arch.ctrl = CTRL_RUNLATCH;
549         /* default to host PVR, since we can't spoof it */
550         vcpu->arch.pvr = mfspr(SPRN_PVR);
551         kvmppc_set_pvr(vcpu, vcpu->arch.pvr);
552         spin_lock_init(&vcpu->arch.vpa_update_lock);
553
554         kvmppc_mmu_book3s_hv_init(vcpu);
555
556         /*
557          * We consider the vcpu stopped until we see the first run ioctl for it.
558          */
559         vcpu->arch.state = KVMPPC_VCPU_STOPPED;
560
561         init_waitqueue_head(&vcpu->arch.cpu_run);
562
563         mutex_lock(&kvm->lock);
564         vcore = kvm->arch.vcores[core];
565         if (!vcore) {
566                 vcore = kzalloc(sizeof(struct kvmppc_vcore), GFP_KERNEL);
567                 if (vcore) {
568                         INIT_LIST_HEAD(&vcore->runnable_threads);
569                         spin_lock_init(&vcore->lock);
570                         init_waitqueue_head(&vcore->wq);
571                 }
572                 kvm->arch.vcores[core] = vcore;
573         }
574         mutex_unlock(&kvm->lock);
575
576         if (!vcore)
577                 goto free_vcpu;
578
579         spin_lock(&vcore->lock);
580         ++vcore->num_threads;
581         spin_unlock(&vcore->lock);
582         vcpu->arch.vcore = vcore;
583
584         vcpu->arch.cpu_type = KVM_CPU_3S_64;
585         kvmppc_sanity_check(vcpu);
586
587         return vcpu;
588
589 free_vcpu:
590         kmem_cache_free(kvm_vcpu_cache, vcpu);
591 out:
592         return ERR_PTR(err);
593 }
594
595 void kvmppc_core_vcpu_free(struct kvm_vcpu *vcpu)
596 {
597         spin_lock(&vcpu->arch.vpa_update_lock);
598         if (vcpu->arch.dtl.pinned_addr)
599                 kvmppc_unpin_guest_page(vcpu->kvm, vcpu->arch.dtl.pinned_addr);
600         if (vcpu->arch.slb_shadow.pinned_addr)
601                 kvmppc_unpin_guest_page(vcpu->kvm, vcpu->arch.slb_shadow.pinned_addr);
602         if (vcpu->arch.vpa.pinned_addr)
603                 kvmppc_unpin_guest_page(vcpu->kvm, vcpu->arch.vpa.pinned_addr);
604         spin_unlock(&vcpu->arch.vpa_update_lock);
605         kvm_vcpu_uninit(vcpu);
606         kmem_cache_free(kvm_vcpu_cache, vcpu);
607 }
608
609 static void kvmppc_set_timer(struct kvm_vcpu *vcpu)
610 {
611         unsigned long dec_nsec, now;
612
613         now = get_tb();
614         if (now > vcpu->arch.dec_expires) {
615                 /* decrementer has already gone negative */
616                 kvmppc_core_queue_dec(vcpu);
617                 kvmppc_core_prepare_to_enter(vcpu);
618                 return;
619         }
620         dec_nsec = (vcpu->arch.dec_expires - now) * NSEC_PER_SEC
621                    / tb_ticks_per_sec;
622         hrtimer_start(&vcpu->arch.dec_timer, ktime_set(0, dec_nsec),
623                       HRTIMER_MODE_REL);
624         vcpu->arch.timer_running = 1;
625 }
626
627 static void kvmppc_end_cede(struct kvm_vcpu *vcpu)
628 {
629         vcpu->arch.ceded = 0;
630         if (vcpu->arch.timer_running) {
631                 hrtimer_try_to_cancel(&vcpu->arch.dec_timer);
632                 vcpu->arch.timer_running = 0;
633         }
634 }
635
636 extern int __kvmppc_vcore_entry(struct kvm_run *kvm_run, struct kvm_vcpu *vcpu);
637 extern void xics_wake_cpu(int cpu);
638
639 static void kvmppc_remove_runnable(struct kvmppc_vcore *vc,
640                                    struct kvm_vcpu *vcpu)
641 {
642         struct kvm_vcpu *v;
643
644         if (vcpu->arch.state != KVMPPC_VCPU_RUNNABLE)
645                 return;
646         vcpu->arch.state = KVMPPC_VCPU_BUSY_IN_HOST;
647         --vc->n_runnable;
648         ++vc->n_busy;
649         /* decrement the physical thread id of each following vcpu */
650         v = vcpu;
651         list_for_each_entry_continue(v, &vc->runnable_threads, arch.run_list)
652                 --v->arch.ptid;
653         list_del(&vcpu->arch.run_list);
654 }
655
656 static int kvmppc_grab_hwthread(int cpu)
657 {
658         struct paca_struct *tpaca;
659         long timeout = 1000;
660
661         tpaca = &paca[cpu];
662
663         /* Ensure the thread won't go into the kernel if it wakes */
664         tpaca->kvm_hstate.hwthread_req = 1;
665
666         /*
667          * If the thread is already executing in the kernel (e.g. handling
668          * a stray interrupt), wait for it to get back to nap mode.
669          * The smp_mb() is to ensure that our setting of hwthread_req
670          * is visible before we look at hwthread_state, so if this
671          * races with the code at system_reset_pSeries and the thread
672          * misses our setting of hwthread_req, we are sure to see its
673          * setting of hwthread_state, and vice versa.
674          */
675         smp_mb();
676         while (tpaca->kvm_hstate.hwthread_state == KVM_HWTHREAD_IN_KERNEL) {
677                 if (--timeout <= 0) {
678                         pr_err("KVM: couldn't grab cpu %d\n", cpu);
679                         return -EBUSY;
680                 }
681                 udelay(1);
682         }
683         return 0;
684 }
685
686 static void kvmppc_release_hwthread(int cpu)
687 {
688         struct paca_struct *tpaca;
689
690         tpaca = &paca[cpu];
691         tpaca->kvm_hstate.hwthread_req = 0;
692         tpaca->kvm_hstate.kvm_vcpu = NULL;
693 }
694
695 static void kvmppc_start_thread(struct kvm_vcpu *vcpu)
696 {
697         int cpu;
698         struct paca_struct *tpaca;
699         struct kvmppc_vcore *vc = vcpu->arch.vcore;
700
701         if (vcpu->arch.timer_running) {
702                 hrtimer_try_to_cancel(&vcpu->arch.dec_timer);
703                 vcpu->arch.timer_running = 0;
704         }
705         cpu = vc->pcpu + vcpu->arch.ptid;
706         tpaca = &paca[cpu];
707         tpaca->kvm_hstate.kvm_vcpu = vcpu;
708         tpaca->kvm_hstate.kvm_vcore = vc;
709         tpaca->kvm_hstate.napping = 0;
710         vcpu->cpu = vc->pcpu;
711         smp_wmb();
712 #if defined(CONFIG_PPC_ICP_NATIVE) && defined(CONFIG_SMP)
713         if (vcpu->arch.ptid) {
714                 kvmppc_grab_hwthread(cpu);
715                 xics_wake_cpu(cpu);
716                 ++vc->n_woken;
717         }
718 #endif
719 }
720
721 static void kvmppc_wait_for_nap(struct kvmppc_vcore *vc)
722 {
723         int i;
724
725         HMT_low();
726         i = 0;
727         while (vc->nap_count < vc->n_woken) {
728                 if (++i >= 1000000) {
729                         pr_err("kvmppc_wait_for_nap timeout %d %d\n",
730                                vc->nap_count, vc->n_woken);
731                         break;
732                 }
733                 cpu_relax();
734         }
735         HMT_medium();
736 }
737
738 /*
739  * Check that we are on thread 0 and that any other threads in
740  * this core are off-line.
741  */
742 static int on_primary_thread(void)
743 {
744         int cpu = smp_processor_id();
745         int thr = cpu_thread_in_core(cpu);
746
747         if (thr)
748                 return 0;
749         while (++thr < threads_per_core)
750                 if (cpu_online(cpu + thr))
751                         return 0;
752         return 1;
753 }
754
755 /*
756  * Run a set of guest threads on a physical core.
757  * Called with vc->lock held.
758  */
759 static int kvmppc_run_core(struct kvmppc_vcore *vc)
760 {
761         struct kvm_vcpu *vcpu, *vcpu0, *vnext;
762         long ret;
763         u64 now;
764         int ptid, i;
765
766         /* don't start if any threads have a signal pending */
767         list_for_each_entry(vcpu, &vc->runnable_threads, arch.run_list)
768                 if (signal_pending(vcpu->arch.run_task))
769                         return 0;
770
771         /*
772          * Make sure we are running on thread 0, and that
773          * secondary threads are offline.
774          * XXX we should also block attempts to bring any
775          * secondary threads online.
776          */
777         if (threads_per_core > 1 && !on_primary_thread()) {
778                 list_for_each_entry(vcpu, &vc->runnable_threads, arch.run_list)
779                         vcpu->arch.ret = -EBUSY;
780                 goto out;
781         }
782
783         /*
784          * Assign physical thread IDs, first to non-ceded vcpus
785          * and then to ceded ones.
786          */
787         ptid = 0;
788         vcpu0 = NULL;
789         list_for_each_entry(vcpu, &vc->runnable_threads, arch.run_list) {
790                 if (!vcpu->arch.ceded) {
791                         if (!ptid)
792                                 vcpu0 = vcpu;
793                         vcpu->arch.ptid = ptid++;
794                 }
795         }
796         if (!vcpu0)
797                 return 0;               /* nothing to run */
798         list_for_each_entry(vcpu, &vc->runnable_threads, arch.run_list)
799                 if (vcpu->arch.ceded)
800                         vcpu->arch.ptid = ptid++;
801
802         vc->n_woken = 0;
803         vc->nap_count = 0;
804         vc->entry_exit_count = 0;
805         vc->vcore_state = VCORE_RUNNING;
806         vc->in_guest = 0;
807         vc->pcpu = smp_processor_id();
808         vc->napping_threads = 0;
809         list_for_each_entry(vcpu, &vc->runnable_threads, arch.run_list) {
810                 kvmppc_start_thread(vcpu);
811                 if (vcpu->arch.vpa.update_pending ||
812                     vcpu->arch.slb_shadow.update_pending ||
813                     vcpu->arch.dtl.update_pending)
814                         kvmppc_update_vpas(vcpu);
815         }
816         /* Grab any remaining hw threads so they can't go into the kernel */
817         for (i = ptid; i < threads_per_core; ++i)
818                 kvmppc_grab_hwthread(vc->pcpu + i);
819
820         preempt_disable();
821         spin_unlock(&vc->lock);
822
823         kvm_guest_enter();
824         __kvmppc_vcore_entry(NULL, vcpu0);
825         for (i = 0; i < threads_per_core; ++i)
826                 kvmppc_release_hwthread(vc->pcpu + i);
827
828         spin_lock(&vc->lock);
829         /* disable sending of IPIs on virtual external irqs */
830         list_for_each_entry(vcpu, &vc->runnable_threads, arch.run_list)
831                 vcpu->cpu = -1;
832         /* wait for secondary threads to finish writing their state to memory */
833         if (vc->nap_count < vc->n_woken)
834                 kvmppc_wait_for_nap(vc);
835         /* prevent other vcpu threads from doing kvmppc_start_thread() now */
836         vc->vcore_state = VCORE_EXITING;
837         spin_unlock(&vc->lock);
838
839         /* make sure updates to secondary vcpu structs are visible now */
840         smp_mb();
841         kvm_guest_exit();
842
843         preempt_enable();
844         kvm_resched(vcpu);
845
846         now = get_tb();
847         list_for_each_entry(vcpu, &vc->runnable_threads, arch.run_list) {
848                 /* cancel pending dec exception if dec is positive */
849                 if (now < vcpu->arch.dec_expires &&
850                     kvmppc_core_pending_dec(vcpu))
851                         kvmppc_core_dequeue_dec(vcpu);
852
853                 ret = RESUME_GUEST;
854                 if (vcpu->arch.trap)
855                         ret = kvmppc_handle_exit(vcpu->arch.kvm_run, vcpu,
856                                                  vcpu->arch.run_task);
857
858                 vcpu->arch.ret = ret;
859                 vcpu->arch.trap = 0;
860
861                 if (vcpu->arch.ceded) {
862                         if (ret != RESUME_GUEST)
863                                 kvmppc_end_cede(vcpu);
864                         else
865                                 kvmppc_set_timer(vcpu);
866                 }
867         }
868
869         spin_lock(&vc->lock);
870  out:
871         vc->vcore_state = VCORE_INACTIVE;
872         list_for_each_entry_safe(vcpu, vnext, &vc->runnable_threads,
873                                  arch.run_list) {
874                 if (vcpu->arch.ret != RESUME_GUEST) {
875                         kvmppc_remove_runnable(vc, vcpu);
876                         wake_up(&vcpu->arch.cpu_run);
877                 }
878         }
879
880         return 1;
881 }
882
883 /*
884  * Wait for some other vcpu thread to execute us, and
885  * wake us up when we need to handle something in the host.
886  */
887 static void kvmppc_wait_for_exec(struct kvm_vcpu *vcpu, int wait_state)
888 {
889         DEFINE_WAIT(wait);
890
891         prepare_to_wait(&vcpu->arch.cpu_run, &wait, wait_state);
892         if (vcpu->arch.state == KVMPPC_VCPU_RUNNABLE)
893                 schedule();
894         finish_wait(&vcpu->arch.cpu_run, &wait);
895 }
896
897 /*
898  * All the vcpus in this vcore are idle, so wait for a decrementer
899  * or external interrupt to one of the vcpus.  vc->lock is held.
900  */
901 static void kvmppc_vcore_blocked(struct kvmppc_vcore *vc)
902 {
903         DEFINE_WAIT(wait);
904         struct kvm_vcpu *v;
905         int all_idle = 1;
906
907         prepare_to_wait(&vc->wq, &wait, TASK_INTERRUPTIBLE);
908         vc->vcore_state = VCORE_SLEEPING;
909         spin_unlock(&vc->lock);
910         list_for_each_entry(v, &vc->runnable_threads, arch.run_list) {
911                 if (!v->arch.ceded || v->arch.pending_exceptions) {
912                         all_idle = 0;
913                         break;
914                 }
915         }
916         if (all_idle)
917                 schedule();
918         finish_wait(&vc->wq, &wait);
919         spin_lock(&vc->lock);
920         vc->vcore_state = VCORE_INACTIVE;
921 }
922
923 static int kvmppc_run_vcpu(struct kvm_run *kvm_run, struct kvm_vcpu *vcpu)
924 {
925         int n_ceded;
926         int prev_state;
927         struct kvmppc_vcore *vc;
928         struct kvm_vcpu *v, *vn;
929
930         kvm_run->exit_reason = 0;
931         vcpu->arch.ret = RESUME_GUEST;
932         vcpu->arch.trap = 0;
933
934         /*
935          * Synchronize with other threads in this virtual core
936          */
937         vc = vcpu->arch.vcore;
938         spin_lock(&vc->lock);
939         vcpu->arch.ceded = 0;
940         vcpu->arch.run_task = current;
941         vcpu->arch.kvm_run = kvm_run;
942         prev_state = vcpu->arch.state;
943         vcpu->arch.state = KVMPPC_VCPU_RUNNABLE;
944         list_add_tail(&vcpu->arch.run_list, &vc->runnable_threads);
945         ++vc->n_runnable;
946
947         /*
948          * This happens the first time this is called for a vcpu.
949          * If the vcore is already running, we may be able to start
950          * this thread straight away and have it join in.
951          */
952         if (prev_state == KVMPPC_VCPU_STOPPED) {
953                 if (vc->vcore_state == VCORE_RUNNING &&
954                     VCORE_EXIT_COUNT(vc) == 0) {
955                         vcpu->arch.ptid = vc->n_runnable - 1;
956                         kvmppc_start_thread(vcpu);
957                 }
958
959         } else if (prev_state == KVMPPC_VCPU_BUSY_IN_HOST)
960                 --vc->n_busy;
961
962         while (vcpu->arch.state == KVMPPC_VCPU_RUNNABLE &&
963                !signal_pending(current)) {
964                 if (vc->n_busy || vc->vcore_state != VCORE_INACTIVE) {
965                         spin_unlock(&vc->lock);
966                         kvmppc_wait_for_exec(vcpu, TASK_INTERRUPTIBLE);
967                         spin_lock(&vc->lock);
968                         continue;
969                 }
970                 n_ceded = 0;
971                 list_for_each_entry(v, &vc->runnable_threads, arch.run_list)
972                         n_ceded += v->arch.ceded;
973                 if (n_ceded == vc->n_runnable)
974                         kvmppc_vcore_blocked(vc);
975                 else
976                         kvmppc_run_core(vc);
977
978                 list_for_each_entry_safe(v, vn, &vc->runnable_threads,
979                                          arch.run_list) {
980                         kvmppc_core_prepare_to_enter(v);
981                         if (signal_pending(v->arch.run_task)) {
982                                 kvmppc_remove_runnable(vc, v);
983                                 v->stat.signal_exits++;
984                                 v->arch.kvm_run->exit_reason = KVM_EXIT_INTR;
985                                 v->arch.ret = -EINTR;
986                                 wake_up(&v->arch.cpu_run);
987                         }
988                 }
989         }
990
991         if (signal_pending(current)) {
992                 if (vc->vcore_state == VCORE_RUNNING ||
993                     vc->vcore_state == VCORE_EXITING) {
994                         spin_unlock(&vc->lock);
995                         kvmppc_wait_for_exec(vcpu, TASK_UNINTERRUPTIBLE);
996                         spin_lock(&vc->lock);
997                 }
998                 if (vcpu->arch.state == KVMPPC_VCPU_RUNNABLE) {
999                         kvmppc_remove_runnable(vc, vcpu);
1000                         vcpu->stat.signal_exits++;
1001                         kvm_run->exit_reason = KVM_EXIT_INTR;
1002                         vcpu->arch.ret = -EINTR;
1003                 }
1004         }
1005
1006         spin_unlock(&vc->lock);
1007         return vcpu->arch.ret;
1008 }
1009
1010 int kvmppc_vcpu_run(struct kvm_run *run, struct kvm_vcpu *vcpu)
1011 {
1012         int r;
1013
1014         if (!vcpu->arch.sane) {
1015                 run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
1016                 return -EINVAL;
1017         }
1018
1019         kvmppc_core_prepare_to_enter(vcpu);
1020
1021         /* No need to go into the guest when all we'll do is come back out */
1022         if (signal_pending(current)) {
1023                 run->exit_reason = KVM_EXIT_INTR;
1024                 return -EINTR;
1025         }
1026
1027         /* On the first time here, set up VRMA or RMA */
1028         if (!vcpu->kvm->arch.rma_setup_done) {
1029                 r = kvmppc_hv_setup_rma(vcpu);
1030                 if (r)
1031                         return r;
1032         }
1033
1034         flush_fp_to_thread(current);
1035         flush_altivec_to_thread(current);
1036         flush_vsx_to_thread(current);
1037         vcpu->arch.wqp = &vcpu->arch.vcore->wq;
1038         vcpu->arch.pgdir = current->mm->pgd;
1039
1040         do {
1041                 r = kvmppc_run_vcpu(run, vcpu);
1042
1043                 if (run->exit_reason == KVM_EXIT_PAPR_HCALL &&
1044                     !(vcpu->arch.shregs.msr & MSR_PR)) {
1045                         r = kvmppc_pseries_do_hcall(vcpu);
1046                         kvmppc_core_prepare_to_enter(vcpu);
1047                 }
1048         } while (r == RESUME_GUEST);
1049         return r;
1050 }
1051
1052 static long kvmppc_stt_npages(unsigned long window_size)
1053 {
1054         return ALIGN((window_size >> SPAPR_TCE_SHIFT)
1055                      * sizeof(u64), PAGE_SIZE) / PAGE_SIZE;
1056 }
1057
1058 static void release_spapr_tce_table(struct kvmppc_spapr_tce_table *stt)
1059 {
1060         struct kvm *kvm = stt->kvm;
1061         int i;
1062
1063         mutex_lock(&kvm->lock);
1064         list_del(&stt->list);
1065         for (i = 0; i < kvmppc_stt_npages(stt->window_size); i++)
1066                 __free_page(stt->pages[i]);
1067         kfree(stt);
1068         mutex_unlock(&kvm->lock);
1069
1070         kvm_put_kvm(kvm);
1071 }
1072
1073 static int kvm_spapr_tce_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
1074 {
1075         struct kvmppc_spapr_tce_table *stt = vma->vm_file->private_data;
1076         struct page *page;
1077
1078         if (vmf->pgoff >= kvmppc_stt_npages(stt->window_size))
1079                 return VM_FAULT_SIGBUS;
1080
1081         page = stt->pages[vmf->pgoff];
1082         get_page(page);
1083         vmf->page = page;
1084         return 0;
1085 }
1086
1087 static const struct vm_operations_struct kvm_spapr_tce_vm_ops = {
1088         .fault = kvm_spapr_tce_fault,
1089 };
1090
1091 static int kvm_spapr_tce_mmap(struct file *file, struct vm_area_struct *vma)
1092 {
1093         vma->vm_ops = &kvm_spapr_tce_vm_ops;
1094         return 0;
1095 }
1096
1097 static int kvm_spapr_tce_release(struct inode *inode, struct file *filp)
1098 {
1099         struct kvmppc_spapr_tce_table *stt = filp->private_data;
1100
1101         release_spapr_tce_table(stt);
1102         return 0;
1103 }
1104
1105 static struct file_operations kvm_spapr_tce_fops = {
1106         .mmap           = kvm_spapr_tce_mmap,
1107         .release        = kvm_spapr_tce_release,
1108 };
1109
1110 long kvm_vm_ioctl_create_spapr_tce(struct kvm *kvm,
1111                                    struct kvm_create_spapr_tce *args)
1112 {
1113         struct kvmppc_spapr_tce_table *stt = NULL;
1114         long npages;
1115         int ret = -ENOMEM;
1116         int i;
1117
1118         /* Check this LIOBN hasn't been previously allocated */
1119         list_for_each_entry(stt, &kvm->arch.spapr_tce_tables, list) {
1120                 if (stt->liobn == args->liobn)
1121                         return -EBUSY;
1122         }
1123
1124         npages = kvmppc_stt_npages(args->window_size);
1125
1126         stt = kzalloc(sizeof(*stt) + npages* sizeof(struct page *),
1127                       GFP_KERNEL);
1128         if (!stt)
1129                 goto fail;
1130
1131         stt->liobn = args->liobn;
1132         stt->window_size = args->window_size;
1133         stt->kvm = kvm;
1134
1135         for (i = 0; i < npages; i++) {
1136                 stt->pages[i] = alloc_page(GFP_KERNEL | __GFP_ZERO);
1137                 if (!stt->pages[i])
1138                         goto fail;
1139         }
1140
1141         kvm_get_kvm(kvm);
1142
1143         mutex_lock(&kvm->lock);
1144         list_add(&stt->list, &kvm->arch.spapr_tce_tables);
1145
1146         mutex_unlock(&kvm->lock);
1147
1148         return anon_inode_getfd("kvm-spapr-tce", &kvm_spapr_tce_fops,
1149                                 stt, O_RDWR);
1150
1151 fail:
1152         if (stt) {
1153                 for (i = 0; i < npages; i++)
1154                         if (stt->pages[i])
1155                                 __free_page(stt->pages[i]);
1156
1157                 kfree(stt);
1158         }
1159         return ret;
1160 }
1161
1162 /* Work out RMLS (real mode limit selector) field value for a given RMA size.
1163    Assumes POWER7 or PPC970. */
1164 static inline int lpcr_rmls(unsigned long rma_size)
1165 {
1166         switch (rma_size) {
1167         case 32ul << 20:        /* 32 MB */
1168                 if (cpu_has_feature(CPU_FTR_ARCH_206))
1169                         return 8;       /* only supported on POWER7 */
1170                 return -1;
1171         case 64ul << 20:        /* 64 MB */
1172                 return 3;
1173         case 128ul << 20:       /* 128 MB */
1174                 return 7;
1175         case 256ul << 20:       /* 256 MB */
1176                 return 4;
1177         case 1ul << 30:         /* 1 GB */
1178                 return 2;
1179         case 16ul << 30:        /* 16 GB */
1180                 return 1;
1181         case 256ul << 30:       /* 256 GB */
1182                 return 0;
1183         default:
1184                 return -1;
1185         }
1186 }
1187
1188 static int kvm_rma_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
1189 {
1190         struct kvmppc_linear_info *ri = vma->vm_file->private_data;
1191         struct page *page;
1192
1193         if (vmf->pgoff >= ri->npages)
1194                 return VM_FAULT_SIGBUS;
1195
1196         page = pfn_to_page(ri->base_pfn + vmf->pgoff);
1197         get_page(page);
1198         vmf->page = page;
1199         return 0;
1200 }
1201
1202 static const struct vm_operations_struct kvm_rma_vm_ops = {
1203         .fault = kvm_rma_fault,
1204 };
1205
1206 static int kvm_rma_mmap(struct file *file, struct vm_area_struct *vma)
1207 {
1208         vma->vm_flags |= VM_RESERVED;
1209         vma->vm_ops = &kvm_rma_vm_ops;
1210         return 0;
1211 }
1212
1213 static int kvm_rma_release(struct inode *inode, struct file *filp)
1214 {
1215         struct kvmppc_linear_info *ri = filp->private_data;
1216
1217         kvm_release_rma(ri);
1218         return 0;
1219 }
1220
1221 static struct file_operations kvm_rma_fops = {
1222         .mmap           = kvm_rma_mmap,
1223         .release        = kvm_rma_release,
1224 };
1225
1226 long kvm_vm_ioctl_allocate_rma(struct kvm *kvm, struct kvm_allocate_rma *ret)
1227 {
1228         struct kvmppc_linear_info *ri;
1229         long fd;
1230
1231         ri = kvm_alloc_rma();
1232         if (!ri)
1233                 return -ENOMEM;
1234
1235         fd = anon_inode_getfd("kvm-rma", &kvm_rma_fops, ri, O_RDWR);
1236         if (fd < 0)
1237                 kvm_release_rma(ri);
1238
1239         ret->rma_size = ri->npages << PAGE_SHIFT;
1240         return fd;
1241 }
1242
1243 /*
1244  * Get (and clear) the dirty memory log for a memory slot.
1245  */
1246 int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm, struct kvm_dirty_log *log)
1247 {
1248         struct kvm_memory_slot *memslot;
1249         int r;
1250         unsigned long n;
1251
1252         mutex_lock(&kvm->slots_lock);
1253
1254         r = -EINVAL;
1255         if (log->slot >= KVM_MEMORY_SLOTS)
1256                 goto out;
1257
1258         memslot = id_to_memslot(kvm->memslots, log->slot);
1259         r = -ENOENT;
1260         if (!memslot->dirty_bitmap)
1261                 goto out;
1262
1263         n = kvm_dirty_bitmap_bytes(memslot);
1264         memset(memslot->dirty_bitmap, 0, n);
1265
1266         r = kvmppc_hv_get_dirty_log(kvm, memslot);
1267         if (r)
1268                 goto out;
1269
1270         r = -EFAULT;
1271         if (copy_to_user(log->dirty_bitmap, memslot->dirty_bitmap, n))
1272                 goto out;
1273
1274         r = 0;
1275 out:
1276         mutex_unlock(&kvm->slots_lock);
1277         return r;
1278 }
1279
1280 static unsigned long slb_pgsize_encoding(unsigned long psize)
1281 {
1282         unsigned long senc = 0;
1283
1284         if (psize > 0x1000) {
1285                 senc = SLB_VSID_L;
1286                 if (psize == 0x10000)
1287                         senc |= SLB_VSID_LP_01;
1288         }
1289         return senc;
1290 }
1291
1292 int kvmppc_core_prepare_memory_region(struct kvm *kvm,
1293                                 struct kvm_userspace_memory_region *mem)
1294 {
1295         unsigned long npages;
1296         unsigned long *phys;
1297
1298         /* Allocate a slot_phys array */
1299         phys = kvm->arch.slot_phys[mem->slot];
1300         if (!kvm->arch.using_mmu_notifiers && !phys) {
1301                 npages = mem->memory_size >> PAGE_SHIFT;
1302                 phys = vzalloc(npages * sizeof(unsigned long));
1303                 if (!phys)
1304                         return -ENOMEM;
1305                 kvm->arch.slot_phys[mem->slot] = phys;
1306                 kvm->arch.slot_npages[mem->slot] = npages;
1307         }
1308
1309         return 0;
1310 }
1311
1312 static void unpin_slot(struct kvm *kvm, int slot_id)
1313 {
1314         unsigned long *physp;
1315         unsigned long j, npages, pfn;
1316         struct page *page;
1317
1318         physp = kvm->arch.slot_phys[slot_id];
1319         npages = kvm->arch.slot_npages[slot_id];
1320         if (physp) {
1321                 spin_lock(&kvm->arch.slot_phys_lock);
1322                 for (j = 0; j < npages; j++) {
1323                         if (!(physp[j] & KVMPPC_GOT_PAGE))
1324                                 continue;
1325                         pfn = physp[j] >> PAGE_SHIFT;
1326                         page = pfn_to_page(pfn);
1327                         if (PageHuge(page))
1328                                 page = compound_head(page);
1329                         SetPageDirty(page);
1330                         put_page(page);
1331                 }
1332                 kvm->arch.slot_phys[slot_id] = NULL;
1333                 spin_unlock(&kvm->arch.slot_phys_lock);
1334                 vfree(physp);
1335         }
1336 }
1337
1338 void kvmppc_core_commit_memory_region(struct kvm *kvm,
1339                                 struct kvm_userspace_memory_region *mem)
1340 {
1341 }
1342
1343 static int kvmppc_hv_setup_rma(struct kvm_vcpu *vcpu)
1344 {
1345         int err = 0;
1346         struct kvm *kvm = vcpu->kvm;
1347         struct kvmppc_linear_info *ri = NULL;
1348         unsigned long hva;
1349         struct kvm_memory_slot *memslot;
1350         struct vm_area_struct *vma;
1351         unsigned long lpcr, senc;
1352         unsigned long psize, porder;
1353         unsigned long rma_size;
1354         unsigned long rmls;
1355         unsigned long *physp;
1356         unsigned long i, npages;
1357
1358         mutex_lock(&kvm->lock);
1359         if (kvm->arch.rma_setup_done)
1360                 goto out;       /* another vcpu beat us to it */
1361
1362         /* Look up the memslot for guest physical address 0 */
1363         memslot = gfn_to_memslot(kvm, 0);
1364
1365         /* We must have some memory at 0 by now */
1366         err = -EINVAL;
1367         if (!memslot || (memslot->flags & KVM_MEMSLOT_INVALID))
1368                 goto out;
1369
1370         /* Look up the VMA for the start of this memory slot */
1371         hva = memslot->userspace_addr;
1372         down_read(&current->mm->mmap_sem);
1373         vma = find_vma(current->mm, hva);
1374         if (!vma || vma->vm_start > hva || (vma->vm_flags & VM_IO))
1375                 goto up_out;
1376
1377         psize = vma_kernel_pagesize(vma);
1378         porder = __ilog2(psize);
1379
1380         /* Is this one of our preallocated RMAs? */
1381         if (vma->vm_file && vma->vm_file->f_op == &kvm_rma_fops &&
1382             hva == vma->vm_start)
1383                 ri = vma->vm_file->private_data;
1384
1385         up_read(&current->mm->mmap_sem);
1386
1387         if (!ri) {
1388                 /* On POWER7, use VRMA; on PPC970, give up */
1389                 err = -EPERM;
1390                 if (cpu_has_feature(CPU_FTR_ARCH_201)) {
1391                         pr_err("KVM: CPU requires an RMO\n");
1392                         goto out;
1393                 }
1394
1395                 /* We can handle 4k, 64k or 16M pages in the VRMA */
1396                 err = -EINVAL;
1397                 if (!(psize == 0x1000 || psize == 0x10000 ||
1398                       psize == 0x1000000))
1399                         goto out;
1400
1401                 /* Update VRMASD field in the LPCR */
1402                 senc = slb_pgsize_encoding(psize);
1403                 kvm->arch.vrma_slb_v = senc | SLB_VSID_B_1T |
1404                         (VRMA_VSID << SLB_VSID_SHIFT_1T);
1405                 lpcr = kvm->arch.lpcr & ~LPCR_VRMASD;
1406                 lpcr |= senc << (LPCR_VRMASD_SH - 4);
1407                 kvm->arch.lpcr = lpcr;
1408
1409                 /* Create HPTEs in the hash page table for the VRMA */
1410                 kvmppc_map_vrma(vcpu, memslot, porder);
1411
1412         } else {
1413                 /* Set up to use an RMO region */
1414                 rma_size = ri->npages;
1415                 if (rma_size > memslot->npages)
1416                         rma_size = memslot->npages;
1417                 rma_size <<= PAGE_SHIFT;
1418                 rmls = lpcr_rmls(rma_size);
1419                 err = -EINVAL;
1420                 if (rmls < 0) {
1421                         pr_err("KVM: Can't use RMA of 0x%lx bytes\n", rma_size);
1422                         goto out;
1423                 }
1424                 atomic_inc(&ri->use_count);
1425                 kvm->arch.rma = ri;
1426
1427                 /* Update LPCR and RMOR */
1428                 lpcr = kvm->arch.lpcr;
1429                 if (cpu_has_feature(CPU_FTR_ARCH_201)) {
1430                         /* PPC970; insert RMLS value (split field) in HID4 */
1431                         lpcr &= ~((1ul << HID4_RMLS0_SH) |
1432                                   (3ul << HID4_RMLS2_SH));
1433                         lpcr |= ((rmls >> 2) << HID4_RMLS0_SH) |
1434                                 ((rmls & 3) << HID4_RMLS2_SH);
1435                         /* RMOR is also in HID4 */
1436                         lpcr |= ((ri->base_pfn >> (26 - PAGE_SHIFT)) & 0xffff)
1437                                 << HID4_RMOR_SH;
1438                 } else {
1439                         /* POWER7 */
1440                         lpcr &= ~(LPCR_VPM0 | LPCR_VRMA_L);
1441                         lpcr |= rmls << LPCR_RMLS_SH;
1442                         kvm->arch.rmor = kvm->arch.rma->base_pfn << PAGE_SHIFT;
1443                 }
1444                 kvm->arch.lpcr = lpcr;
1445                 pr_info("KVM: Using RMO at %lx size %lx (LPCR = %lx)\n",
1446                         ri->base_pfn << PAGE_SHIFT, rma_size, lpcr);
1447
1448                 /* Initialize phys addrs of pages in RMO */
1449                 npages = ri->npages;
1450                 porder = __ilog2(npages);
1451                 physp = kvm->arch.slot_phys[memslot->id];
1452                 spin_lock(&kvm->arch.slot_phys_lock);
1453                 for (i = 0; i < npages; ++i)
1454                         physp[i] = ((ri->base_pfn + i) << PAGE_SHIFT) + porder;
1455                 spin_unlock(&kvm->arch.slot_phys_lock);
1456         }
1457
1458         /* Order updates to kvm->arch.lpcr etc. vs. rma_setup_done */
1459         smp_wmb();
1460         kvm->arch.rma_setup_done = 1;
1461         err = 0;
1462  out:
1463         mutex_unlock(&kvm->lock);
1464         return err;
1465
1466  up_out:
1467         up_read(&current->mm->mmap_sem);
1468         goto out;
1469 }
1470
1471 int kvmppc_core_init_vm(struct kvm *kvm)
1472 {
1473         long r;
1474         unsigned long lpcr;
1475
1476         /* Allocate hashed page table */
1477         r = kvmppc_alloc_hpt(kvm);
1478         if (r)
1479                 return r;
1480
1481         INIT_LIST_HEAD(&kvm->arch.spapr_tce_tables);
1482
1483         kvm->arch.rma = NULL;
1484
1485         kvm->arch.host_sdr1 = mfspr(SPRN_SDR1);
1486
1487         if (cpu_has_feature(CPU_FTR_ARCH_201)) {
1488                 /* PPC970; HID4 is effectively the LPCR */
1489                 unsigned long lpid = kvm->arch.lpid;
1490                 kvm->arch.host_lpid = 0;
1491                 kvm->arch.host_lpcr = lpcr = mfspr(SPRN_HID4);
1492                 lpcr &= ~((3 << HID4_LPID1_SH) | (0xful << HID4_LPID5_SH));
1493                 lpcr |= ((lpid >> 4) << HID4_LPID1_SH) |
1494                         ((lpid & 0xf) << HID4_LPID5_SH);
1495         } else {
1496                 /* POWER7; init LPCR for virtual RMA mode */
1497                 kvm->arch.host_lpid = mfspr(SPRN_LPID);
1498                 kvm->arch.host_lpcr = lpcr = mfspr(SPRN_LPCR);
1499                 lpcr &= LPCR_PECE | LPCR_LPES;
1500                 lpcr |= (4UL << LPCR_DPFD_SH) | LPCR_HDICE |
1501                         LPCR_VPM0 | LPCR_VPM1;
1502                 kvm->arch.vrma_slb_v = SLB_VSID_B_1T |
1503                         (VRMA_VSID << SLB_VSID_SHIFT_1T);
1504         }
1505         kvm->arch.lpcr = lpcr;
1506
1507         kvm->arch.using_mmu_notifiers = !!cpu_has_feature(CPU_FTR_ARCH_206);
1508         spin_lock_init(&kvm->arch.slot_phys_lock);
1509         return 0;
1510 }
1511
1512 void kvmppc_core_destroy_vm(struct kvm *kvm)
1513 {
1514         unsigned long i;
1515
1516         if (!kvm->arch.using_mmu_notifiers)
1517                 for (i = 0; i < KVM_MEM_SLOTS_NUM; i++)
1518                         unpin_slot(kvm, i);
1519
1520         if (kvm->arch.rma) {
1521                 kvm_release_rma(kvm->arch.rma);
1522                 kvm->arch.rma = NULL;
1523         }
1524
1525         kvmppc_free_hpt(kvm);
1526         WARN_ON(!list_empty(&kvm->arch.spapr_tce_tables));
1527 }
1528
1529 /* These are stubs for now */
1530 void kvmppc_mmu_pte_pflush(struct kvm_vcpu *vcpu, ulong pa_start, ulong pa_end)
1531 {
1532 }
1533
1534 /* We don't need to emulate any privileged instructions or dcbz */
1535 int kvmppc_core_emulate_op(struct kvm_run *run, struct kvm_vcpu *vcpu,
1536                            unsigned int inst, int *advance)
1537 {
1538         return EMULATE_FAIL;
1539 }
1540
1541 int kvmppc_core_emulate_mtspr(struct kvm_vcpu *vcpu, int sprn, int rs)
1542 {
1543         return EMULATE_FAIL;
1544 }
1545
1546 int kvmppc_core_emulate_mfspr(struct kvm_vcpu *vcpu, int sprn, int rt)
1547 {
1548         return EMULATE_FAIL;
1549 }
1550
1551 static int kvmppc_book3s_hv_init(void)
1552 {
1553         int r;
1554
1555         r = kvm_init(NULL, sizeof(struct kvm_vcpu), 0, THIS_MODULE);
1556
1557         if (r)
1558                 return r;
1559
1560         r = kvmppc_mmu_hv_init();
1561
1562         return r;
1563 }
1564
1565 static void kvmppc_book3s_hv_exit(void)
1566 {
1567         kvm_exit();
1568 }
1569
1570 module_init(kvmppc_book3s_hv_init);
1571 module_exit(kvmppc_book3s_hv_exit);