OSDN Git Service

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