KVM: PPC: Book3S HV: Make HTAB code LE host aware
[linux-2.6-microblaze.git] / arch / powerpc / kvm / book3s_64_mmu_hv.c
1 /*
2  * This program is free software; you can redistribute it and/or modify
3  * it under the terms of the GNU General Public License, version 2, as
4  * published by the Free Software Foundation.
5  *
6  * This program is distributed in the hope that it will be useful,
7  * but WITHOUT ANY WARRANTY; without even the implied warranty of
8  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
9  * GNU General Public License for more details.
10  *
11  * You should have received a copy of the GNU General Public License
12  * along with this program; if not, write to the Free Software
13  * Foundation, 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
14  *
15  * Copyright 2010 Paul Mackerras, IBM Corp. <paulus@au1.ibm.com>
16  */
17
18 #include <linux/types.h>
19 #include <linux/string.h>
20 #include <linux/kvm.h>
21 #include <linux/kvm_host.h>
22 #include <linux/highmem.h>
23 #include <linux/gfp.h>
24 #include <linux/slab.h>
25 #include <linux/hugetlb.h>
26 #include <linux/vmalloc.h>
27 #include <linux/srcu.h>
28 #include <linux/anon_inodes.h>
29 #include <linux/file.h>
30
31 #include <asm/tlbflush.h>
32 #include <asm/kvm_ppc.h>
33 #include <asm/kvm_book3s.h>
34 #include <asm/mmu-hash64.h>
35 #include <asm/hvcall.h>
36 #include <asm/synch.h>
37 #include <asm/ppc-opcode.h>
38 #include <asm/cputable.h>
39
40 #include "book3s_hv_cma.h"
41
42 /* POWER7 has 10-bit LPIDs, PPC970 has 6-bit LPIDs */
43 #define MAX_LPID_970    63
44
45 /* Power architecture requires HPT is at least 256kB */
46 #define PPC_MIN_HPT_ORDER       18
47
48 static long kvmppc_virtmode_do_h_enter(struct kvm *kvm, unsigned long flags,
49                                 long pte_index, unsigned long pteh,
50                                 unsigned long ptel, unsigned long *pte_idx_ret);
51 static void kvmppc_rmap_reset(struct kvm *kvm);
52
53 long kvmppc_alloc_hpt(struct kvm *kvm, u32 *htab_orderp)
54 {
55         unsigned long hpt = 0;
56         struct revmap_entry *rev;
57         struct page *page = NULL;
58         long order = KVM_DEFAULT_HPT_ORDER;
59
60         if (htab_orderp) {
61                 order = *htab_orderp;
62                 if (order < PPC_MIN_HPT_ORDER)
63                         order = PPC_MIN_HPT_ORDER;
64         }
65
66         kvm->arch.hpt_cma_alloc = 0;
67         VM_BUG_ON(order < KVM_CMA_CHUNK_ORDER);
68         page = kvm_alloc_hpt(1 << (order - PAGE_SHIFT));
69         if (page) {
70                 hpt = (unsigned long)pfn_to_kaddr(page_to_pfn(page));
71                 kvm->arch.hpt_cma_alloc = 1;
72         }
73
74         /* Lastly try successively smaller sizes from the page allocator */
75         while (!hpt && order > PPC_MIN_HPT_ORDER) {
76                 hpt = __get_free_pages(GFP_KERNEL|__GFP_ZERO|__GFP_REPEAT|
77                                        __GFP_NOWARN, order - PAGE_SHIFT);
78                 if (!hpt)
79                         --order;
80         }
81
82         if (!hpt)
83                 return -ENOMEM;
84
85         kvm->arch.hpt_virt = hpt;
86         kvm->arch.hpt_order = order;
87         /* HPTEs are 2**4 bytes long */
88         kvm->arch.hpt_npte = 1ul << (order - 4);
89         /* 128 (2**7) bytes in each HPTEG */
90         kvm->arch.hpt_mask = (1ul << (order - 7)) - 1;
91
92         /* Allocate reverse map array */
93         rev = vmalloc(sizeof(struct revmap_entry) * kvm->arch.hpt_npte);
94         if (!rev) {
95                 pr_err("kvmppc_alloc_hpt: Couldn't alloc reverse map array\n");
96                 goto out_freehpt;
97         }
98         kvm->arch.revmap = rev;
99         kvm->arch.sdr1 = __pa(hpt) | (order - 18);
100
101         pr_info("KVM guest htab at %lx (order %ld), LPID %x\n",
102                 hpt, order, kvm->arch.lpid);
103
104         if (htab_orderp)
105                 *htab_orderp = order;
106         return 0;
107
108  out_freehpt:
109         if (kvm->arch.hpt_cma_alloc)
110                 kvm_release_hpt(page, 1 << (order - PAGE_SHIFT));
111         else
112                 free_pages(hpt, order - PAGE_SHIFT);
113         return -ENOMEM;
114 }
115
116 long kvmppc_alloc_reset_hpt(struct kvm *kvm, u32 *htab_orderp)
117 {
118         long err = -EBUSY;
119         long order;
120
121         mutex_lock(&kvm->lock);
122         if (kvm->arch.rma_setup_done) {
123                 kvm->arch.rma_setup_done = 0;
124                 /* order rma_setup_done vs. vcpus_running */
125                 smp_mb();
126                 if (atomic_read(&kvm->arch.vcpus_running)) {
127                         kvm->arch.rma_setup_done = 1;
128                         goto out;
129                 }
130         }
131         if (kvm->arch.hpt_virt) {
132                 order = kvm->arch.hpt_order;
133                 /* Set the entire HPT to 0, i.e. invalid HPTEs */
134                 memset((void *)kvm->arch.hpt_virt, 0, 1ul << order);
135                 /*
136                  * Reset all the reverse-mapping chains for all memslots
137                  */
138                 kvmppc_rmap_reset(kvm);
139                 /* Ensure that each vcpu will flush its TLB on next entry. */
140                 cpumask_setall(&kvm->arch.need_tlb_flush);
141                 *htab_orderp = order;
142                 err = 0;
143         } else {
144                 err = kvmppc_alloc_hpt(kvm, htab_orderp);
145                 order = *htab_orderp;
146         }
147  out:
148         mutex_unlock(&kvm->lock);
149         return err;
150 }
151
152 void kvmppc_free_hpt(struct kvm *kvm)
153 {
154         kvmppc_free_lpid(kvm->arch.lpid);
155         vfree(kvm->arch.revmap);
156         if (kvm->arch.hpt_cma_alloc)
157                 kvm_release_hpt(virt_to_page(kvm->arch.hpt_virt),
158                                 1 << (kvm->arch.hpt_order - PAGE_SHIFT));
159         else
160                 free_pages(kvm->arch.hpt_virt,
161                            kvm->arch.hpt_order - PAGE_SHIFT);
162 }
163
164 /* Bits in first HPTE dword for pagesize 4k, 64k or 16M */
165 static inline unsigned long hpte0_pgsize_encoding(unsigned long pgsize)
166 {
167         return (pgsize > 0x1000) ? HPTE_V_LARGE : 0;
168 }
169
170 /* Bits in second HPTE dword for pagesize 4k, 64k or 16M */
171 static inline unsigned long hpte1_pgsize_encoding(unsigned long pgsize)
172 {
173         return (pgsize == 0x10000) ? 0x1000 : 0;
174 }
175
176 void kvmppc_map_vrma(struct kvm_vcpu *vcpu, struct kvm_memory_slot *memslot,
177                      unsigned long porder)
178 {
179         unsigned long i;
180         unsigned long npages;
181         unsigned long hp_v, hp_r;
182         unsigned long addr, hash;
183         unsigned long psize;
184         unsigned long hp0, hp1;
185         unsigned long idx_ret;
186         long ret;
187         struct kvm *kvm = vcpu->kvm;
188
189         psize = 1ul << porder;
190         npages = memslot->npages >> (porder - PAGE_SHIFT);
191
192         /* VRMA can't be > 1TB */
193         if (npages > 1ul << (40 - porder))
194                 npages = 1ul << (40 - porder);
195         /* Can't use more than 1 HPTE per HPTEG */
196         if (npages > kvm->arch.hpt_mask + 1)
197                 npages = kvm->arch.hpt_mask + 1;
198
199         hp0 = HPTE_V_1TB_SEG | (VRMA_VSID << (40 - 16)) |
200                 HPTE_V_BOLTED | hpte0_pgsize_encoding(psize);
201         hp1 = hpte1_pgsize_encoding(psize) |
202                 HPTE_R_R | HPTE_R_C | HPTE_R_M | PP_RWXX;
203
204         for (i = 0; i < npages; ++i) {
205                 addr = i << porder;
206                 /* can't use hpt_hash since va > 64 bits */
207                 hash = (i ^ (VRMA_VSID ^ (VRMA_VSID << 25))) & kvm->arch.hpt_mask;
208                 /*
209                  * We assume that the hash table is empty and no
210                  * vcpus are using it at this stage.  Since we create
211                  * at most one HPTE per HPTEG, we just assume entry 7
212                  * is available and use it.
213                  */
214                 hash = (hash << 3) + 7;
215                 hp_v = hp0 | ((addr >> 16) & ~0x7fUL);
216                 hp_r = hp1 | addr;
217                 ret = kvmppc_virtmode_do_h_enter(kvm, H_EXACT, hash, hp_v, hp_r,
218                                                  &idx_ret);
219                 if (ret != H_SUCCESS) {
220                         pr_err("KVM: map_vrma at %lx failed, ret=%ld\n",
221                                addr, ret);
222                         break;
223                 }
224         }
225 }
226
227 int kvmppc_mmu_hv_init(void)
228 {
229         unsigned long host_lpid, rsvd_lpid;
230
231         if (!cpu_has_feature(CPU_FTR_HVMODE))
232                 return -EINVAL;
233
234         /* POWER7 has 10-bit LPIDs, PPC970 and e500mc have 6-bit LPIDs */
235         if (cpu_has_feature(CPU_FTR_ARCH_206)) {
236                 host_lpid = mfspr(SPRN_LPID);   /* POWER7 */
237                 rsvd_lpid = LPID_RSVD;
238         } else {
239                 host_lpid = 0;                  /* PPC970 */
240                 rsvd_lpid = MAX_LPID_970;
241         }
242
243         kvmppc_init_lpid(rsvd_lpid + 1);
244
245         kvmppc_claim_lpid(host_lpid);
246         /* rsvd_lpid is reserved for use in partition switching */
247         kvmppc_claim_lpid(rsvd_lpid);
248
249         return 0;
250 }
251
252 static void kvmppc_mmu_book3s_64_hv_reset_msr(struct kvm_vcpu *vcpu)
253 {
254         unsigned long msr = vcpu->arch.intr_msr;
255
256         /* If transactional, change to suspend mode on IRQ delivery */
257         if (MSR_TM_TRANSACTIONAL(vcpu->arch.shregs.msr))
258                 msr |= MSR_TS_S;
259         else
260                 msr |= vcpu->arch.shregs.msr & MSR_TS_MASK;
261         kvmppc_set_msr(vcpu, msr);
262 }
263
264 /*
265  * This is called to get a reference to a guest page if there isn't
266  * one already in the memslot->arch.slot_phys[] array.
267  */
268 static long kvmppc_get_guest_page(struct kvm *kvm, unsigned long gfn,
269                                   struct kvm_memory_slot *memslot,
270                                   unsigned long psize)
271 {
272         unsigned long start;
273         long np, err;
274         struct page *page, *hpage, *pages[1];
275         unsigned long s, pgsize;
276         unsigned long *physp;
277         unsigned int is_io, got, pgorder;
278         struct vm_area_struct *vma;
279         unsigned long pfn, i, npages;
280
281         physp = memslot->arch.slot_phys;
282         if (!physp)
283                 return -EINVAL;
284         if (physp[gfn - memslot->base_gfn])
285                 return 0;
286
287         is_io = 0;
288         got = 0;
289         page = NULL;
290         pgsize = psize;
291         err = -EINVAL;
292         start = gfn_to_hva_memslot(memslot, gfn);
293
294         /* Instantiate and get the page we want access to */
295         np = get_user_pages_fast(start, 1, 1, pages);
296         if (np != 1) {
297                 /* Look up the vma for the page */
298                 down_read(&current->mm->mmap_sem);
299                 vma = find_vma(current->mm, start);
300                 if (!vma || vma->vm_start > start ||
301                     start + psize > vma->vm_end ||
302                     !(vma->vm_flags & VM_PFNMAP))
303                         goto up_err;
304                 is_io = hpte_cache_bits(pgprot_val(vma->vm_page_prot));
305                 pfn = vma->vm_pgoff + ((start - vma->vm_start) >> PAGE_SHIFT);
306                 /* check alignment of pfn vs. requested page size */
307                 if (psize > PAGE_SIZE && (pfn & ((psize >> PAGE_SHIFT) - 1)))
308                         goto up_err;
309                 up_read(&current->mm->mmap_sem);
310
311         } else {
312                 page = pages[0];
313                 got = KVMPPC_GOT_PAGE;
314
315                 /* See if this is a large page */
316                 s = PAGE_SIZE;
317                 if (PageHuge(page)) {
318                         hpage = compound_head(page);
319                         s <<= compound_order(hpage);
320                         /* Get the whole large page if slot alignment is ok */
321                         if (s > psize && slot_is_aligned(memslot, s) &&
322                             !(memslot->userspace_addr & (s - 1))) {
323                                 start &= ~(s - 1);
324                                 pgsize = s;
325                                 get_page(hpage);
326                                 put_page(page);
327                                 page = hpage;
328                         }
329                 }
330                 if (s < psize)
331                         goto out;
332                 pfn = page_to_pfn(page);
333         }
334
335         npages = pgsize >> PAGE_SHIFT;
336         pgorder = __ilog2(npages);
337         physp += (gfn - memslot->base_gfn) & ~(npages - 1);
338         spin_lock(&kvm->arch.slot_phys_lock);
339         for (i = 0; i < npages; ++i) {
340                 if (!physp[i]) {
341                         physp[i] = ((pfn + i) << PAGE_SHIFT) +
342                                 got + is_io + pgorder;
343                         got = 0;
344                 }
345         }
346         spin_unlock(&kvm->arch.slot_phys_lock);
347         err = 0;
348
349  out:
350         if (got)
351                 put_page(page);
352         return err;
353
354  up_err:
355         up_read(&current->mm->mmap_sem);
356         return err;
357 }
358
359 long kvmppc_virtmode_do_h_enter(struct kvm *kvm, unsigned long flags,
360                                 long pte_index, unsigned long pteh,
361                                 unsigned long ptel, unsigned long *pte_idx_ret)
362 {
363         unsigned long psize, gpa, gfn;
364         struct kvm_memory_slot *memslot;
365         long ret;
366
367         if (kvm->arch.using_mmu_notifiers)
368                 goto do_insert;
369
370         psize = hpte_page_size(pteh, ptel);
371         if (!psize)
372                 return H_PARAMETER;
373
374         pteh &= ~(HPTE_V_HVLOCK | HPTE_V_ABSENT | HPTE_V_VALID);
375
376         /* Find the memslot (if any) for this address */
377         gpa = (ptel & HPTE_R_RPN) & ~(psize - 1);
378         gfn = gpa >> PAGE_SHIFT;
379         memslot = gfn_to_memslot(kvm, gfn);
380         if (memslot && !(memslot->flags & KVM_MEMSLOT_INVALID)) {
381                 if (!slot_is_aligned(memslot, psize))
382                         return H_PARAMETER;
383                 if (kvmppc_get_guest_page(kvm, gfn, memslot, psize) < 0)
384                         return H_PARAMETER;
385         }
386
387  do_insert:
388         /* Protect linux PTE lookup from page table destruction */
389         rcu_read_lock_sched();  /* this disables preemption too */
390         ret = kvmppc_do_h_enter(kvm, flags, pte_index, pteh, ptel,
391                                 current->mm->pgd, false, pte_idx_ret);
392         rcu_read_unlock_sched();
393         if (ret == H_TOO_HARD) {
394                 /* this can't happen */
395                 pr_err("KVM: Oops, kvmppc_h_enter returned too hard!\n");
396                 ret = H_RESOURCE;       /* or something */
397         }
398         return ret;
399
400 }
401
402 /*
403  * We come here on a H_ENTER call from the guest when we are not
404  * using mmu notifiers and we don't have the requested page pinned
405  * already.
406  */
407 long kvmppc_virtmode_h_enter(struct kvm_vcpu *vcpu, unsigned long flags,
408                              long pte_index, unsigned long pteh,
409                              unsigned long ptel)
410 {
411         return kvmppc_virtmode_do_h_enter(vcpu->kvm, flags, pte_index,
412                                           pteh, ptel, &vcpu->arch.gpr[4]);
413 }
414
415 static struct kvmppc_slb *kvmppc_mmu_book3s_hv_find_slbe(struct kvm_vcpu *vcpu,
416                                                          gva_t eaddr)
417 {
418         u64 mask;
419         int i;
420
421         for (i = 0; i < vcpu->arch.slb_nr; i++) {
422                 if (!(vcpu->arch.slb[i].orige & SLB_ESID_V))
423                         continue;
424
425                 if (vcpu->arch.slb[i].origv & SLB_VSID_B_1T)
426                         mask = ESID_MASK_1T;
427                 else
428                         mask = ESID_MASK;
429
430                 if (((vcpu->arch.slb[i].orige ^ eaddr) & mask) == 0)
431                         return &vcpu->arch.slb[i];
432         }
433         return NULL;
434 }
435
436 static unsigned long kvmppc_mmu_get_real_addr(unsigned long v, unsigned long r,
437                         unsigned long ea)
438 {
439         unsigned long ra_mask;
440
441         ra_mask = hpte_page_size(v, r) - 1;
442         return (r & HPTE_R_RPN & ~ra_mask) | (ea & ra_mask);
443 }
444
445 static int kvmppc_mmu_book3s_64_hv_xlate(struct kvm_vcpu *vcpu, gva_t eaddr,
446                         struct kvmppc_pte *gpte, bool data, bool iswrite)
447 {
448         struct kvm *kvm = vcpu->kvm;
449         struct kvmppc_slb *slbe;
450         unsigned long slb_v;
451         unsigned long pp, key;
452         unsigned long v, gr;
453         __be64 *hptep;
454         int index;
455         int virtmode = vcpu->arch.shregs.msr & (data ? MSR_DR : MSR_IR);
456
457         /* Get SLB entry */
458         if (virtmode) {
459                 slbe = kvmppc_mmu_book3s_hv_find_slbe(vcpu, eaddr);
460                 if (!slbe)
461                         return -EINVAL;
462                 slb_v = slbe->origv;
463         } else {
464                 /* real mode access */
465                 slb_v = vcpu->kvm->arch.vrma_slb_v;
466         }
467
468         preempt_disable();
469         /* Find the HPTE in the hash table */
470         index = kvmppc_hv_find_lock_hpte(kvm, eaddr, slb_v,
471                                          HPTE_V_VALID | HPTE_V_ABSENT);
472         if (index < 0) {
473                 preempt_enable();
474                 return -ENOENT;
475         }
476         hptep = (__be64 *)(kvm->arch.hpt_virt + (index << 4));
477         v = be64_to_cpu(hptep[0]) & ~HPTE_V_HVLOCK;
478         gr = kvm->arch.revmap[index].guest_rpte;
479
480         /* Unlock the HPTE */
481         asm volatile("lwsync" : : : "memory");
482         hptep[0] = cpu_to_be64(v);
483         preempt_enable();
484
485         gpte->eaddr = eaddr;
486         gpte->vpage = ((v & HPTE_V_AVPN) << 4) | ((eaddr >> 12) & 0xfff);
487
488         /* Get PP bits and key for permission check */
489         pp = gr & (HPTE_R_PP0 | HPTE_R_PP);
490         key = (vcpu->arch.shregs.msr & MSR_PR) ? SLB_VSID_KP : SLB_VSID_KS;
491         key &= slb_v;
492
493         /* Calculate permissions */
494         gpte->may_read = hpte_read_permission(pp, key);
495         gpte->may_write = hpte_write_permission(pp, key);
496         gpte->may_execute = gpte->may_read && !(gr & (HPTE_R_N | HPTE_R_G));
497
498         /* Storage key permission check for POWER7 */
499         if (data && virtmode && cpu_has_feature(CPU_FTR_ARCH_206)) {
500                 int amrfield = hpte_get_skey_perm(gr, vcpu->arch.amr);
501                 if (amrfield & 1)
502                         gpte->may_read = 0;
503                 if (amrfield & 2)
504                         gpte->may_write = 0;
505         }
506
507         /* Get the guest physical address */
508         gpte->raddr = kvmppc_mmu_get_real_addr(v, gr, eaddr);
509         return 0;
510 }
511
512 /*
513  * Quick test for whether an instruction is a load or a store.
514  * If the instruction is a load or a store, then this will indicate
515  * which it is, at least on server processors.  (Embedded processors
516  * have some external PID instructions that don't follow the rule
517  * embodied here.)  If the instruction isn't a load or store, then
518  * this doesn't return anything useful.
519  */
520 static int instruction_is_store(unsigned int instr)
521 {
522         unsigned int mask;
523
524         mask = 0x10000000;
525         if ((instr & 0xfc000000) == 0x7c000000)
526                 mask = 0x100;           /* major opcode 31 */
527         return (instr & mask) != 0;
528 }
529
530 static int kvmppc_hv_emulate_mmio(struct kvm_run *run, struct kvm_vcpu *vcpu,
531                                   unsigned long gpa, gva_t ea, int is_store)
532 {
533         int ret;
534         u32 last_inst;
535         unsigned long srr0 = kvmppc_get_pc(vcpu);
536
537         /* We try to load the last instruction.  We don't let
538          * emulate_instruction do it as it doesn't check what
539          * kvmppc_ld returns.
540          * If we fail, we just return to the guest and try executing it again.
541          */
542         if (vcpu->arch.last_inst == KVM_INST_FETCH_FAILED) {
543                 ret = kvmppc_ld(vcpu, &srr0, sizeof(u32), &last_inst, false);
544                 if (ret != EMULATE_DONE || last_inst == KVM_INST_FETCH_FAILED)
545                         return RESUME_GUEST;
546                 vcpu->arch.last_inst = last_inst;
547         }
548
549         /*
550          * WARNING: We do not know for sure whether the instruction we just
551          * read from memory is the same that caused the fault in the first
552          * place.  If the instruction we read is neither an load or a store,
553          * then it can't access memory, so we don't need to worry about
554          * enforcing access permissions.  So, assuming it is a load or
555          * store, we just check that its direction (load or store) is
556          * consistent with the original fault, since that's what we
557          * checked the access permissions against.  If there is a mismatch
558          * we just return and retry the instruction.
559          */
560
561         if (instruction_is_store(kvmppc_get_last_inst(vcpu)) != !!is_store)
562                 return RESUME_GUEST;
563
564         /*
565          * Emulated accesses are emulated by looking at the hash for
566          * translation once, then performing the access later. The
567          * translation could be invalidated in the meantime in which
568          * point performing the subsequent memory access on the old
569          * physical address could possibly be a security hole for the
570          * guest (but not the host).
571          *
572          * This is less of an issue for MMIO stores since they aren't
573          * globally visible. It could be an issue for MMIO loads to
574          * a certain extent but we'll ignore it for now.
575          */
576
577         vcpu->arch.paddr_accessed = gpa;
578         vcpu->arch.vaddr_accessed = ea;
579         return kvmppc_emulate_mmio(run, vcpu);
580 }
581
582 int kvmppc_book3s_hv_page_fault(struct kvm_run *run, struct kvm_vcpu *vcpu,
583                                 unsigned long ea, unsigned long dsisr)
584 {
585         struct kvm *kvm = vcpu->kvm;
586         unsigned long hpte[3], r;
587         __be64 *hptep;
588         unsigned long mmu_seq, psize, pte_size;
589         unsigned long gpa_base, gfn_base;
590         unsigned long gpa, gfn, hva, pfn;
591         struct kvm_memory_slot *memslot;
592         unsigned long *rmap;
593         struct revmap_entry *rev;
594         struct page *page, *pages[1];
595         long index, ret, npages;
596         unsigned long is_io;
597         unsigned int writing, write_ok;
598         struct vm_area_struct *vma;
599         unsigned long rcbits;
600
601         /*
602          * Real-mode code has already searched the HPT and found the
603          * entry we're interested in.  Lock the entry and check that
604          * it hasn't changed.  If it has, just return and re-execute the
605          * instruction.
606          */
607         if (ea != vcpu->arch.pgfault_addr)
608                 return RESUME_GUEST;
609         index = vcpu->arch.pgfault_index;
610         hptep = (__be64 *)(kvm->arch.hpt_virt + (index << 4));
611         rev = &kvm->arch.revmap[index];
612         preempt_disable();
613         while (!try_lock_hpte(hptep, HPTE_V_HVLOCK))
614                 cpu_relax();
615         hpte[0] = be64_to_cpu(hptep[0]) & ~HPTE_V_HVLOCK;
616         hpte[1] = be64_to_cpu(hptep[1]);
617         hpte[2] = r = rev->guest_rpte;
618         asm volatile("lwsync" : : : "memory");
619         hptep[0] = cpu_to_be64(hpte[0]);
620         preempt_enable();
621
622         if (hpte[0] != vcpu->arch.pgfault_hpte[0] ||
623             hpte[1] != vcpu->arch.pgfault_hpte[1])
624                 return RESUME_GUEST;
625
626         /* Translate the logical address and get the page */
627         psize = hpte_page_size(hpte[0], r);
628         gpa_base = r & HPTE_R_RPN & ~(psize - 1);
629         gfn_base = gpa_base >> PAGE_SHIFT;
630         gpa = gpa_base | (ea & (psize - 1));
631         gfn = gpa >> PAGE_SHIFT;
632         memslot = gfn_to_memslot(kvm, gfn);
633
634         /* No memslot means it's an emulated MMIO region */
635         if (!memslot || (memslot->flags & KVM_MEMSLOT_INVALID))
636                 return kvmppc_hv_emulate_mmio(run, vcpu, gpa, ea,
637                                               dsisr & DSISR_ISSTORE);
638
639         if (!kvm->arch.using_mmu_notifiers)
640                 return -EFAULT;         /* should never get here */
641
642         /*
643          * This should never happen, because of the slot_is_aligned()
644          * check in kvmppc_do_h_enter().
645          */
646         if (gfn_base < memslot->base_gfn)
647                 return -EFAULT;
648
649         /* used to check for invalidations in progress */
650         mmu_seq = kvm->mmu_notifier_seq;
651         smp_rmb();
652
653         is_io = 0;
654         pfn = 0;
655         page = NULL;
656         pte_size = PAGE_SIZE;
657         writing = (dsisr & DSISR_ISSTORE) != 0;
658         /* If writing != 0, then the HPTE must allow writing, if we get here */
659         write_ok = writing;
660         hva = gfn_to_hva_memslot(memslot, gfn);
661         npages = get_user_pages_fast(hva, 1, writing, pages);
662         if (npages < 1) {
663                 /* Check if it's an I/O mapping */
664                 down_read(&current->mm->mmap_sem);
665                 vma = find_vma(current->mm, hva);
666                 if (vma && vma->vm_start <= hva && hva + psize <= vma->vm_end &&
667                     (vma->vm_flags & VM_PFNMAP)) {
668                         pfn = vma->vm_pgoff +
669                                 ((hva - vma->vm_start) >> PAGE_SHIFT);
670                         pte_size = psize;
671                         is_io = hpte_cache_bits(pgprot_val(vma->vm_page_prot));
672                         write_ok = vma->vm_flags & VM_WRITE;
673                 }
674                 up_read(&current->mm->mmap_sem);
675                 if (!pfn)
676                         return -EFAULT;
677         } else {
678                 page = pages[0];
679                 pfn = page_to_pfn(page);
680                 if (PageHuge(page)) {
681                         page = compound_head(page);
682                         pte_size <<= compound_order(page);
683                 }
684                 /* if the guest wants write access, see if that is OK */
685                 if (!writing && hpte_is_writable(r)) {
686                         unsigned int hugepage_shift;
687                         pte_t *ptep, pte;
688
689                         /*
690                          * We need to protect against page table destruction
691                          * while looking up and updating the pte.
692                          */
693                         rcu_read_lock_sched();
694                         ptep = find_linux_pte_or_hugepte(current->mm->pgd,
695                                                          hva, &hugepage_shift);
696                         if (ptep) {
697                                 pte = kvmppc_read_update_linux_pte(ptep, 1,
698                                                            hugepage_shift);
699                                 if (pte_write(pte))
700                                         write_ok = 1;
701                         }
702                         rcu_read_unlock_sched();
703                 }
704         }
705
706         ret = -EFAULT;
707         if (psize > pte_size)
708                 goto out_put;
709
710         /* Check WIMG vs. the actual page we're accessing */
711         if (!hpte_cache_flags_ok(r, is_io)) {
712                 if (is_io)
713                         return -EFAULT;
714                 /*
715                  * Allow guest to map emulated device memory as
716                  * uncacheable, but actually make it cacheable.
717                  */
718                 r = (r & ~(HPTE_R_W|HPTE_R_I|HPTE_R_G)) | HPTE_R_M;
719         }
720
721         /*
722          * Set the HPTE to point to pfn.
723          * Since the pfn is at PAGE_SIZE granularity, make sure we
724          * don't mask out lower-order bits if psize < PAGE_SIZE.
725          */
726         if (psize < PAGE_SIZE)
727                 psize = PAGE_SIZE;
728         r = (r & ~(HPTE_R_PP0 - psize)) | ((pfn << PAGE_SHIFT) & ~(psize - 1));
729         if (hpte_is_writable(r) && !write_ok)
730                 r = hpte_make_readonly(r);
731         ret = RESUME_GUEST;
732         preempt_disable();
733         while (!try_lock_hpte(hptep, HPTE_V_HVLOCK))
734                 cpu_relax();
735         if ((be64_to_cpu(hptep[0]) & ~HPTE_V_HVLOCK) != hpte[0] ||
736                 be64_to_cpu(hptep[1]) != hpte[1] ||
737                 rev->guest_rpte != hpte[2])
738                 /* HPTE has been changed under us; let the guest retry */
739                 goto out_unlock;
740         hpte[0] = (hpte[0] & ~HPTE_V_ABSENT) | HPTE_V_VALID;
741
742         /* Always put the HPTE in the rmap chain for the page base address */
743         rmap = &memslot->arch.rmap[gfn_base - memslot->base_gfn];
744         lock_rmap(rmap);
745
746         /* Check if we might have been invalidated; let the guest retry if so */
747         ret = RESUME_GUEST;
748         if (mmu_notifier_retry(vcpu->kvm, mmu_seq)) {
749                 unlock_rmap(rmap);
750                 goto out_unlock;
751         }
752
753         /* Only set R/C in real HPTE if set in both *rmap and guest_rpte */
754         rcbits = *rmap >> KVMPPC_RMAP_RC_SHIFT;
755         r &= rcbits | ~(HPTE_R_R | HPTE_R_C);
756
757         if (be64_to_cpu(hptep[0]) & HPTE_V_VALID) {
758                 /* HPTE was previously valid, so we need to invalidate it */
759                 unlock_rmap(rmap);
760                 hptep[0] |= cpu_to_be64(HPTE_V_ABSENT);
761                 kvmppc_invalidate_hpte(kvm, hptep, index);
762                 /* don't lose previous R and C bits */
763                 r |= be64_to_cpu(hptep[1]) & (HPTE_R_R | HPTE_R_C);
764         } else {
765                 kvmppc_add_revmap_chain(kvm, rev, rmap, index, 0);
766         }
767
768         hptep[1] = cpu_to_be64(r);
769         eieio();
770         hptep[0] = cpu_to_be64(hpte[0]);
771         asm volatile("ptesync" : : : "memory");
772         preempt_enable();
773         if (page && hpte_is_writable(r))
774                 SetPageDirty(page);
775
776  out_put:
777         if (page) {
778                 /*
779                  * We drop pages[0] here, not page because page might
780                  * have been set to the head page of a compound, but
781                  * we have to drop the reference on the correct tail
782                  * page to match the get inside gup()
783                  */
784                 put_page(pages[0]);
785         }
786         return ret;
787
788  out_unlock:
789         hptep[0] &= ~cpu_to_be64(HPTE_V_HVLOCK);
790         preempt_enable();
791         goto out_put;
792 }
793
794 static void kvmppc_rmap_reset(struct kvm *kvm)
795 {
796         struct kvm_memslots *slots;
797         struct kvm_memory_slot *memslot;
798         int srcu_idx;
799
800         srcu_idx = srcu_read_lock(&kvm->srcu);
801         slots = kvm->memslots;
802         kvm_for_each_memslot(memslot, slots) {
803                 /*
804                  * This assumes it is acceptable to lose reference and
805                  * change bits across a reset.
806                  */
807                 memset(memslot->arch.rmap, 0,
808                        memslot->npages * sizeof(*memslot->arch.rmap));
809         }
810         srcu_read_unlock(&kvm->srcu, srcu_idx);
811 }
812
813 static int kvm_handle_hva_range(struct kvm *kvm,
814                                 unsigned long start,
815                                 unsigned long end,
816                                 int (*handler)(struct kvm *kvm,
817                                                unsigned long *rmapp,
818                                                unsigned long gfn))
819 {
820         int ret;
821         int retval = 0;
822         struct kvm_memslots *slots;
823         struct kvm_memory_slot *memslot;
824
825         slots = kvm_memslots(kvm);
826         kvm_for_each_memslot(memslot, slots) {
827                 unsigned long hva_start, hva_end;
828                 gfn_t gfn, gfn_end;
829
830                 hva_start = max(start, memslot->userspace_addr);
831                 hva_end = min(end, memslot->userspace_addr +
832                                         (memslot->npages << PAGE_SHIFT));
833                 if (hva_start >= hva_end)
834                         continue;
835                 /*
836                  * {gfn(page) | page intersects with [hva_start, hva_end)} =
837                  * {gfn, gfn+1, ..., gfn_end-1}.
838                  */
839                 gfn = hva_to_gfn_memslot(hva_start, memslot);
840                 gfn_end = hva_to_gfn_memslot(hva_end + PAGE_SIZE - 1, memslot);
841
842                 for (; gfn < gfn_end; ++gfn) {
843                         gfn_t gfn_offset = gfn - memslot->base_gfn;
844
845                         ret = handler(kvm, &memslot->arch.rmap[gfn_offset], gfn);
846                         retval |= ret;
847                 }
848         }
849
850         return retval;
851 }
852
853 static int kvm_handle_hva(struct kvm *kvm, unsigned long hva,
854                           int (*handler)(struct kvm *kvm, unsigned long *rmapp,
855                                          unsigned long gfn))
856 {
857         return kvm_handle_hva_range(kvm, hva, hva + 1, handler);
858 }
859
860 static int kvm_unmap_rmapp(struct kvm *kvm, unsigned long *rmapp,
861                            unsigned long gfn)
862 {
863         struct revmap_entry *rev = kvm->arch.revmap;
864         unsigned long h, i, j;
865         __be64 *hptep;
866         unsigned long ptel, psize, rcbits;
867
868         for (;;) {
869                 lock_rmap(rmapp);
870                 if (!(*rmapp & KVMPPC_RMAP_PRESENT)) {
871                         unlock_rmap(rmapp);
872                         break;
873                 }
874
875                 /*
876                  * To avoid an ABBA deadlock with the HPTE lock bit,
877                  * we can't spin on the HPTE lock while holding the
878                  * rmap chain lock.
879                  */
880                 i = *rmapp & KVMPPC_RMAP_INDEX;
881                 hptep = (__be64 *) (kvm->arch.hpt_virt + (i << 4));
882                 if (!try_lock_hpte(hptep, HPTE_V_HVLOCK)) {
883                         /* unlock rmap before spinning on the HPTE lock */
884                         unlock_rmap(rmapp);
885                         while (be64_to_cpu(hptep[0]) & HPTE_V_HVLOCK)
886                                 cpu_relax();
887                         continue;
888                 }
889                 j = rev[i].forw;
890                 if (j == i) {
891                         /* chain is now empty */
892                         *rmapp &= ~(KVMPPC_RMAP_PRESENT | KVMPPC_RMAP_INDEX);
893                 } else {
894                         /* remove i from chain */
895                         h = rev[i].back;
896                         rev[h].forw = j;
897                         rev[j].back = h;
898                         rev[i].forw = rev[i].back = i;
899                         *rmapp = (*rmapp & ~KVMPPC_RMAP_INDEX) | j;
900                 }
901
902                 /* Now check and modify the HPTE */
903                 ptel = rev[i].guest_rpte;
904                 psize = hpte_page_size(be64_to_cpu(hptep[0]), ptel);
905                 if ((be64_to_cpu(hptep[0]) & HPTE_V_VALID) &&
906                     hpte_rpn(ptel, psize) == gfn) {
907                         if (kvm->arch.using_mmu_notifiers)
908                                 hptep[0] |= cpu_to_be64(HPTE_V_ABSENT);
909                         kvmppc_invalidate_hpte(kvm, hptep, i);
910                         /* Harvest R and C */
911                         rcbits = be64_to_cpu(hptep[1]) & (HPTE_R_R | HPTE_R_C);
912                         *rmapp |= rcbits << KVMPPC_RMAP_RC_SHIFT;
913                         if (rcbits & ~rev[i].guest_rpte) {
914                                 rev[i].guest_rpte = ptel | rcbits;
915                                 note_hpte_modification(kvm, &rev[i]);
916                         }
917                 }
918                 unlock_rmap(rmapp);
919                 hptep[0] &= ~cpu_to_be64(HPTE_V_HVLOCK);
920         }
921         return 0;
922 }
923
924 int kvm_unmap_hva_hv(struct kvm *kvm, unsigned long hva)
925 {
926         if (kvm->arch.using_mmu_notifiers)
927                 kvm_handle_hva(kvm, hva, kvm_unmap_rmapp);
928         return 0;
929 }
930
931 int kvm_unmap_hva_range_hv(struct kvm *kvm, unsigned long start, unsigned long end)
932 {
933         if (kvm->arch.using_mmu_notifiers)
934                 kvm_handle_hva_range(kvm, start, end, kvm_unmap_rmapp);
935         return 0;
936 }
937
938 void kvmppc_core_flush_memslot_hv(struct kvm *kvm,
939                                   struct kvm_memory_slot *memslot)
940 {
941         unsigned long *rmapp;
942         unsigned long gfn;
943         unsigned long n;
944
945         rmapp = memslot->arch.rmap;
946         gfn = memslot->base_gfn;
947         for (n = memslot->npages; n; --n) {
948                 /*
949                  * Testing the present bit without locking is OK because
950                  * the memslot has been marked invalid already, and hence
951                  * no new HPTEs referencing this page can be created,
952                  * thus the present bit can't go from 0 to 1.
953                  */
954                 if (*rmapp & KVMPPC_RMAP_PRESENT)
955                         kvm_unmap_rmapp(kvm, rmapp, gfn);
956                 ++rmapp;
957                 ++gfn;
958         }
959 }
960
961 static int kvm_age_rmapp(struct kvm *kvm, unsigned long *rmapp,
962                          unsigned long gfn)
963 {
964         struct revmap_entry *rev = kvm->arch.revmap;
965         unsigned long head, i, j;
966         __be64 *hptep;
967         int ret = 0;
968
969  retry:
970         lock_rmap(rmapp);
971         if (*rmapp & KVMPPC_RMAP_REFERENCED) {
972                 *rmapp &= ~KVMPPC_RMAP_REFERENCED;
973                 ret = 1;
974         }
975         if (!(*rmapp & KVMPPC_RMAP_PRESENT)) {
976                 unlock_rmap(rmapp);
977                 return ret;
978         }
979
980         i = head = *rmapp & KVMPPC_RMAP_INDEX;
981         do {
982                 hptep = (__be64 *) (kvm->arch.hpt_virt + (i << 4));
983                 j = rev[i].forw;
984
985                 /* If this HPTE isn't referenced, ignore it */
986                 if (!(be64_to_cpu(hptep[1]) & HPTE_R_R))
987                         continue;
988
989                 if (!try_lock_hpte(hptep, HPTE_V_HVLOCK)) {
990                         /* unlock rmap before spinning on the HPTE lock */
991                         unlock_rmap(rmapp);
992                         while (be64_to_cpu(hptep[0]) & HPTE_V_HVLOCK)
993                                 cpu_relax();
994                         goto retry;
995                 }
996
997                 /* Now check and modify the HPTE */
998                 if ((be64_to_cpu(hptep[0]) & HPTE_V_VALID) &&
999                     (be64_to_cpu(hptep[1]) & HPTE_R_R)) {
1000                         kvmppc_clear_ref_hpte(kvm, hptep, i);
1001                         if (!(rev[i].guest_rpte & HPTE_R_R)) {
1002                                 rev[i].guest_rpte |= HPTE_R_R;
1003                                 note_hpte_modification(kvm, &rev[i]);
1004                         }
1005                         ret = 1;
1006                 }
1007                 hptep[0] &= ~cpu_to_be64(HPTE_V_HVLOCK);
1008         } while ((i = j) != head);
1009
1010         unlock_rmap(rmapp);
1011         return ret;
1012 }
1013
1014 int kvm_age_hva_hv(struct kvm *kvm, unsigned long hva)
1015 {
1016         if (!kvm->arch.using_mmu_notifiers)
1017                 return 0;
1018         return kvm_handle_hva(kvm, hva, kvm_age_rmapp);
1019 }
1020
1021 static int kvm_test_age_rmapp(struct kvm *kvm, unsigned long *rmapp,
1022                               unsigned long gfn)
1023 {
1024         struct revmap_entry *rev = kvm->arch.revmap;
1025         unsigned long head, i, j;
1026         unsigned long *hp;
1027         int ret = 1;
1028
1029         if (*rmapp & KVMPPC_RMAP_REFERENCED)
1030                 return 1;
1031
1032         lock_rmap(rmapp);
1033         if (*rmapp & KVMPPC_RMAP_REFERENCED)
1034                 goto out;
1035
1036         if (*rmapp & KVMPPC_RMAP_PRESENT) {
1037                 i = head = *rmapp & KVMPPC_RMAP_INDEX;
1038                 do {
1039                         hp = (unsigned long *)(kvm->arch.hpt_virt + (i << 4));
1040                         j = rev[i].forw;
1041                         if (be64_to_cpu(hp[1]) & HPTE_R_R)
1042                                 goto out;
1043                 } while ((i = j) != head);
1044         }
1045         ret = 0;
1046
1047  out:
1048         unlock_rmap(rmapp);
1049         return ret;
1050 }
1051
1052 int kvm_test_age_hva_hv(struct kvm *kvm, unsigned long hva)
1053 {
1054         if (!kvm->arch.using_mmu_notifiers)
1055                 return 0;
1056         return kvm_handle_hva(kvm, hva, kvm_test_age_rmapp);
1057 }
1058
1059 void kvm_set_spte_hva_hv(struct kvm *kvm, unsigned long hva, pte_t pte)
1060 {
1061         if (!kvm->arch.using_mmu_notifiers)
1062                 return;
1063         kvm_handle_hva(kvm, hva, kvm_unmap_rmapp);
1064 }
1065
1066 static int vcpus_running(struct kvm *kvm)
1067 {
1068         return atomic_read(&kvm->arch.vcpus_running) != 0;
1069 }
1070
1071 /*
1072  * Returns the number of system pages that are dirty.
1073  * This can be more than 1 if we find a huge-page HPTE.
1074  */
1075 static int kvm_test_clear_dirty_npages(struct kvm *kvm, unsigned long *rmapp)
1076 {
1077         struct revmap_entry *rev = kvm->arch.revmap;
1078         unsigned long head, i, j;
1079         unsigned long n;
1080         unsigned long v, r;
1081         __be64 *hptep;
1082         int npages_dirty = 0;
1083
1084  retry:
1085         lock_rmap(rmapp);
1086         if (*rmapp & KVMPPC_RMAP_CHANGED) {
1087                 *rmapp &= ~KVMPPC_RMAP_CHANGED;
1088                 npages_dirty = 1;
1089         }
1090         if (!(*rmapp & KVMPPC_RMAP_PRESENT)) {
1091                 unlock_rmap(rmapp);
1092                 return npages_dirty;
1093         }
1094
1095         i = head = *rmapp & KVMPPC_RMAP_INDEX;
1096         do {
1097                 unsigned long hptep1;
1098                 hptep = (__be64 *) (kvm->arch.hpt_virt + (i << 4));
1099                 j = rev[i].forw;
1100
1101                 /*
1102                  * Checking the C (changed) bit here is racy since there
1103                  * is no guarantee about when the hardware writes it back.
1104                  * If the HPTE is not writable then it is stable since the
1105                  * page can't be written to, and we would have done a tlbie
1106                  * (which forces the hardware to complete any writeback)
1107                  * when making the HPTE read-only.
1108                  * If vcpus are running then this call is racy anyway
1109                  * since the page could get dirtied subsequently, so we
1110                  * expect there to be a further call which would pick up
1111                  * any delayed C bit writeback.
1112                  * Otherwise we need to do the tlbie even if C==0 in
1113                  * order to pick up any delayed writeback of C.
1114                  */
1115                 hptep1 = be64_to_cpu(hptep[1]);
1116                 if (!(hptep1 & HPTE_R_C) &&
1117                     (!hpte_is_writable(hptep1) || vcpus_running(kvm)))
1118                         continue;
1119
1120                 if (!try_lock_hpte(hptep, HPTE_V_HVLOCK)) {
1121                         /* unlock rmap before spinning on the HPTE lock */
1122                         unlock_rmap(rmapp);
1123                         while (hptep[0] & cpu_to_be64(HPTE_V_HVLOCK))
1124                                 cpu_relax();
1125                         goto retry;
1126                 }
1127
1128                 /* Now check and modify the HPTE */
1129                 if (!(hptep[0] & cpu_to_be64(HPTE_V_VALID)))
1130                         continue;
1131
1132                 /* need to make it temporarily absent so C is stable */
1133                 hptep[0] |= cpu_to_be64(HPTE_V_ABSENT);
1134                 kvmppc_invalidate_hpte(kvm, hptep, i);
1135                 v = be64_to_cpu(hptep[0]);
1136                 r = be64_to_cpu(hptep[1]);
1137                 if (r & HPTE_R_C) {
1138                         hptep[1] = cpu_to_be64(r & ~HPTE_R_C);
1139                         if (!(rev[i].guest_rpte & HPTE_R_C)) {
1140                                 rev[i].guest_rpte |= HPTE_R_C;
1141                                 note_hpte_modification(kvm, &rev[i]);
1142                         }
1143                         n = hpte_page_size(v, r);
1144                         n = (n + PAGE_SIZE - 1) >> PAGE_SHIFT;
1145                         if (n > npages_dirty)
1146                                 npages_dirty = n;
1147                         eieio();
1148                 }
1149                 v &= ~(HPTE_V_ABSENT | HPTE_V_HVLOCK);
1150                 v |= HPTE_V_VALID;
1151                 hptep[0] = cpu_to_be64(v);
1152         } while ((i = j) != head);
1153
1154         unlock_rmap(rmapp);
1155         return npages_dirty;
1156 }
1157
1158 static void harvest_vpa_dirty(struct kvmppc_vpa *vpa,
1159                               struct kvm_memory_slot *memslot,
1160                               unsigned long *map)
1161 {
1162         unsigned long gfn;
1163
1164         if (!vpa->dirty || !vpa->pinned_addr)
1165                 return;
1166         gfn = vpa->gpa >> PAGE_SHIFT;
1167         if (gfn < memslot->base_gfn ||
1168             gfn >= memslot->base_gfn + memslot->npages)
1169                 return;
1170
1171         vpa->dirty = false;
1172         if (map)
1173                 __set_bit_le(gfn - memslot->base_gfn, map);
1174 }
1175
1176 long kvmppc_hv_get_dirty_log(struct kvm *kvm, struct kvm_memory_slot *memslot,
1177                              unsigned long *map)
1178 {
1179         unsigned long i, j;
1180         unsigned long *rmapp;
1181         struct kvm_vcpu *vcpu;
1182
1183         preempt_disable();
1184         rmapp = memslot->arch.rmap;
1185         for (i = 0; i < memslot->npages; ++i) {
1186                 int npages = kvm_test_clear_dirty_npages(kvm, rmapp);
1187                 /*
1188                  * Note that if npages > 0 then i must be a multiple of npages,
1189                  * since we always put huge-page HPTEs in the rmap chain
1190                  * corresponding to their page base address.
1191                  */
1192                 if (npages && map)
1193                         for (j = i; npages; ++j, --npages)
1194                                 __set_bit_le(j, map);
1195                 ++rmapp;
1196         }
1197
1198         /* Harvest dirty bits from VPA and DTL updates */
1199         /* Note: we never modify the SLB shadow buffer areas */
1200         kvm_for_each_vcpu(i, vcpu, kvm) {
1201                 spin_lock(&vcpu->arch.vpa_update_lock);
1202                 harvest_vpa_dirty(&vcpu->arch.vpa, memslot, map);
1203                 harvest_vpa_dirty(&vcpu->arch.dtl, memslot, map);
1204                 spin_unlock(&vcpu->arch.vpa_update_lock);
1205         }
1206         preempt_enable();
1207         return 0;
1208 }
1209
1210 void *kvmppc_pin_guest_page(struct kvm *kvm, unsigned long gpa,
1211                             unsigned long *nb_ret)
1212 {
1213         struct kvm_memory_slot *memslot;
1214         unsigned long gfn = gpa >> PAGE_SHIFT;
1215         struct page *page, *pages[1];
1216         int npages;
1217         unsigned long hva, offset;
1218         unsigned long pa;
1219         unsigned long *physp;
1220         int srcu_idx;
1221
1222         srcu_idx = srcu_read_lock(&kvm->srcu);
1223         memslot = gfn_to_memslot(kvm, gfn);
1224         if (!memslot || (memslot->flags & KVM_MEMSLOT_INVALID))
1225                 goto err;
1226         if (!kvm->arch.using_mmu_notifiers) {
1227                 physp = memslot->arch.slot_phys;
1228                 if (!physp)
1229                         goto err;
1230                 physp += gfn - memslot->base_gfn;
1231                 pa = *physp;
1232                 if (!pa) {
1233                         if (kvmppc_get_guest_page(kvm, gfn, memslot,
1234                                                   PAGE_SIZE) < 0)
1235                                 goto err;
1236                         pa = *physp;
1237                 }
1238                 page = pfn_to_page(pa >> PAGE_SHIFT);
1239                 get_page(page);
1240         } else {
1241                 hva = gfn_to_hva_memslot(memslot, gfn);
1242                 npages = get_user_pages_fast(hva, 1, 1, pages);
1243                 if (npages < 1)
1244                         goto err;
1245                 page = pages[0];
1246         }
1247         srcu_read_unlock(&kvm->srcu, srcu_idx);
1248
1249         offset = gpa & (PAGE_SIZE - 1);
1250         if (nb_ret)
1251                 *nb_ret = PAGE_SIZE - offset;
1252         return page_address(page) + offset;
1253
1254  err:
1255         srcu_read_unlock(&kvm->srcu, srcu_idx);
1256         return NULL;
1257 }
1258
1259 void kvmppc_unpin_guest_page(struct kvm *kvm, void *va, unsigned long gpa,
1260                              bool dirty)
1261 {
1262         struct page *page = virt_to_page(va);
1263         struct kvm_memory_slot *memslot;
1264         unsigned long gfn;
1265         unsigned long *rmap;
1266         int srcu_idx;
1267
1268         put_page(page);
1269
1270         if (!dirty || !kvm->arch.using_mmu_notifiers)
1271                 return;
1272
1273         /* We need to mark this page dirty in the rmap chain */
1274         gfn = gpa >> PAGE_SHIFT;
1275         srcu_idx = srcu_read_lock(&kvm->srcu);
1276         memslot = gfn_to_memslot(kvm, gfn);
1277         if (memslot) {
1278                 rmap = &memslot->arch.rmap[gfn - memslot->base_gfn];
1279                 lock_rmap(rmap);
1280                 *rmap |= KVMPPC_RMAP_CHANGED;
1281                 unlock_rmap(rmap);
1282         }
1283         srcu_read_unlock(&kvm->srcu, srcu_idx);
1284 }
1285
1286 /*
1287  * Functions for reading and writing the hash table via reads and
1288  * writes on a file descriptor.
1289  *
1290  * Reads return the guest view of the hash table, which has to be
1291  * pieced together from the real hash table and the guest_rpte
1292  * values in the revmap array.
1293  *
1294  * On writes, each HPTE written is considered in turn, and if it
1295  * is valid, it is written to the HPT as if an H_ENTER with the
1296  * exact flag set was done.  When the invalid count is non-zero
1297  * in the header written to the stream, the kernel will make
1298  * sure that that many HPTEs are invalid, and invalidate them
1299  * if not.
1300  */
1301
1302 struct kvm_htab_ctx {
1303         unsigned long   index;
1304         unsigned long   flags;
1305         struct kvm      *kvm;
1306         int             first_pass;
1307 };
1308
1309 #define HPTE_SIZE       (2 * sizeof(unsigned long))
1310
1311 /*
1312  * Returns 1 if this HPT entry has been modified or has pending
1313  * R/C bit changes.
1314  */
1315 static int hpte_dirty(struct revmap_entry *revp, __be64 *hptp)
1316 {
1317         unsigned long rcbits_unset;
1318
1319         if (revp->guest_rpte & HPTE_GR_MODIFIED)
1320                 return 1;
1321
1322         /* Also need to consider changes in reference and changed bits */
1323         rcbits_unset = ~revp->guest_rpte & (HPTE_R_R | HPTE_R_C);
1324         if ((be64_to_cpu(hptp[0]) & HPTE_V_VALID) &&
1325             (be64_to_cpu(hptp[1]) & rcbits_unset))
1326                 return 1;
1327
1328         return 0;
1329 }
1330
1331 static long record_hpte(unsigned long flags, __be64 *hptp,
1332                         unsigned long *hpte, struct revmap_entry *revp,
1333                         int want_valid, int first_pass)
1334 {
1335         unsigned long v, r;
1336         unsigned long rcbits_unset;
1337         int ok = 1;
1338         int valid, dirty;
1339
1340         /* Unmodified entries are uninteresting except on the first pass */
1341         dirty = hpte_dirty(revp, hptp);
1342         if (!first_pass && !dirty)
1343                 return 0;
1344
1345         valid = 0;
1346         if (be64_to_cpu(hptp[0]) & (HPTE_V_VALID | HPTE_V_ABSENT)) {
1347                 valid = 1;
1348                 if ((flags & KVM_GET_HTAB_BOLTED_ONLY) &&
1349                     !(be64_to_cpu(hptp[0]) & HPTE_V_BOLTED))
1350                         valid = 0;
1351         }
1352         if (valid != want_valid)
1353                 return 0;
1354
1355         v = r = 0;
1356         if (valid || dirty) {
1357                 /* lock the HPTE so it's stable and read it */
1358                 preempt_disable();
1359                 while (!try_lock_hpte(hptp, HPTE_V_HVLOCK))
1360                         cpu_relax();
1361                 v = be64_to_cpu(hptp[0]);
1362
1363                 /* re-evaluate valid and dirty from synchronized HPTE value */
1364                 valid = !!(v & HPTE_V_VALID);
1365                 dirty = !!(revp->guest_rpte & HPTE_GR_MODIFIED);
1366
1367                 /* Harvest R and C into guest view if necessary */
1368                 rcbits_unset = ~revp->guest_rpte & (HPTE_R_R | HPTE_R_C);
1369                 if (valid && (rcbits_unset & be64_to_cpu(hptp[1]))) {
1370                         revp->guest_rpte |= (be64_to_cpu(hptp[1]) &
1371                                 (HPTE_R_R | HPTE_R_C)) | HPTE_GR_MODIFIED;
1372                         dirty = 1;
1373                 }
1374
1375                 if (v & HPTE_V_ABSENT) {
1376                         v &= ~HPTE_V_ABSENT;
1377                         v |= HPTE_V_VALID;
1378                         valid = 1;
1379                 }
1380                 if ((flags & KVM_GET_HTAB_BOLTED_ONLY) && !(v & HPTE_V_BOLTED))
1381                         valid = 0;
1382
1383                 r = revp->guest_rpte;
1384                 /* only clear modified if this is the right sort of entry */
1385                 if (valid == want_valid && dirty) {
1386                         r &= ~HPTE_GR_MODIFIED;
1387                         revp->guest_rpte = r;
1388                 }
1389                 asm volatile(PPC_RELEASE_BARRIER "" : : : "memory");
1390                 hptp[0] &= ~cpu_to_be64(HPTE_V_HVLOCK);
1391                 preempt_enable();
1392                 if (!(valid == want_valid && (first_pass || dirty)))
1393                         ok = 0;
1394         }
1395         hpte[0] = cpu_to_be64(v);
1396         hpte[1] = cpu_to_be64(r);
1397         return ok;
1398 }
1399
1400 static ssize_t kvm_htab_read(struct file *file, char __user *buf,
1401                              size_t count, loff_t *ppos)
1402 {
1403         struct kvm_htab_ctx *ctx = file->private_data;
1404         struct kvm *kvm = ctx->kvm;
1405         struct kvm_get_htab_header hdr;
1406         __be64 *hptp;
1407         struct revmap_entry *revp;
1408         unsigned long i, nb, nw;
1409         unsigned long __user *lbuf;
1410         struct kvm_get_htab_header __user *hptr;
1411         unsigned long flags;
1412         int first_pass;
1413         unsigned long hpte[2];
1414
1415         if (!access_ok(VERIFY_WRITE, buf, count))
1416                 return -EFAULT;
1417
1418         first_pass = ctx->first_pass;
1419         flags = ctx->flags;
1420
1421         i = ctx->index;
1422         hptp = (__be64 *)(kvm->arch.hpt_virt + (i * HPTE_SIZE));
1423         revp = kvm->arch.revmap + i;
1424         lbuf = (unsigned long __user *)buf;
1425
1426         nb = 0;
1427         while (nb + sizeof(hdr) + HPTE_SIZE < count) {
1428                 /* Initialize header */
1429                 hptr = (struct kvm_get_htab_header __user *)buf;
1430                 hdr.n_valid = 0;
1431                 hdr.n_invalid = 0;
1432                 nw = nb;
1433                 nb += sizeof(hdr);
1434                 lbuf = (unsigned long __user *)(buf + sizeof(hdr));
1435
1436                 /* Skip uninteresting entries, i.e. clean on not-first pass */
1437                 if (!first_pass) {
1438                         while (i < kvm->arch.hpt_npte &&
1439                                !hpte_dirty(revp, hptp)) {
1440                                 ++i;
1441                                 hptp += 2;
1442                                 ++revp;
1443                         }
1444                 }
1445                 hdr.index = i;
1446
1447                 /* Grab a series of valid entries */
1448                 while (i < kvm->arch.hpt_npte &&
1449                        hdr.n_valid < 0xffff &&
1450                        nb + HPTE_SIZE < count &&
1451                        record_hpte(flags, hptp, hpte, revp, 1, first_pass)) {
1452                         /* valid entry, write it out */
1453                         ++hdr.n_valid;
1454                         if (__put_user(hpte[0], lbuf) ||
1455                             __put_user(hpte[1], lbuf + 1))
1456                                 return -EFAULT;
1457                         nb += HPTE_SIZE;
1458                         lbuf += 2;
1459                         ++i;
1460                         hptp += 2;
1461                         ++revp;
1462                 }
1463                 /* Now skip invalid entries while we can */
1464                 while (i < kvm->arch.hpt_npte &&
1465                        hdr.n_invalid < 0xffff &&
1466                        record_hpte(flags, hptp, hpte, revp, 0, first_pass)) {
1467                         /* found an invalid entry */
1468                         ++hdr.n_invalid;
1469                         ++i;
1470                         hptp += 2;
1471                         ++revp;
1472                 }
1473
1474                 if (hdr.n_valid || hdr.n_invalid) {
1475                         /* write back the header */
1476                         if (__copy_to_user(hptr, &hdr, sizeof(hdr)))
1477                                 return -EFAULT;
1478                         nw = nb;
1479                         buf = (char __user *)lbuf;
1480                 } else {
1481                         nb = nw;
1482                 }
1483
1484                 /* Check if we've wrapped around the hash table */
1485                 if (i >= kvm->arch.hpt_npte) {
1486                         i = 0;
1487                         ctx->first_pass = 0;
1488                         break;
1489                 }
1490         }
1491
1492         ctx->index = i;
1493
1494         return nb;
1495 }
1496
1497 static ssize_t kvm_htab_write(struct file *file, const char __user *buf,
1498                               size_t count, loff_t *ppos)
1499 {
1500         struct kvm_htab_ctx *ctx = file->private_data;
1501         struct kvm *kvm = ctx->kvm;
1502         struct kvm_get_htab_header hdr;
1503         unsigned long i, j;
1504         unsigned long v, r;
1505         unsigned long __user *lbuf;
1506         __be64 *hptp;
1507         unsigned long tmp[2];
1508         ssize_t nb;
1509         long int err, ret;
1510         int rma_setup;
1511
1512         if (!access_ok(VERIFY_READ, buf, count))
1513                 return -EFAULT;
1514
1515         /* lock out vcpus from running while we're doing this */
1516         mutex_lock(&kvm->lock);
1517         rma_setup = kvm->arch.rma_setup_done;
1518         if (rma_setup) {
1519                 kvm->arch.rma_setup_done = 0;   /* temporarily */
1520                 /* order rma_setup_done vs. vcpus_running */
1521                 smp_mb();
1522                 if (atomic_read(&kvm->arch.vcpus_running)) {
1523                         kvm->arch.rma_setup_done = 1;
1524                         mutex_unlock(&kvm->lock);
1525                         return -EBUSY;
1526                 }
1527         }
1528
1529         err = 0;
1530         for (nb = 0; nb + sizeof(hdr) <= count; ) {
1531                 err = -EFAULT;
1532                 if (__copy_from_user(&hdr, buf, sizeof(hdr)))
1533                         break;
1534
1535                 err = 0;
1536                 if (nb + hdr.n_valid * HPTE_SIZE > count)
1537                         break;
1538
1539                 nb += sizeof(hdr);
1540                 buf += sizeof(hdr);
1541
1542                 err = -EINVAL;
1543                 i = hdr.index;
1544                 if (i >= kvm->arch.hpt_npte ||
1545                     i + hdr.n_valid + hdr.n_invalid > kvm->arch.hpt_npte)
1546                         break;
1547
1548                 hptp = (__be64 *)(kvm->arch.hpt_virt + (i * HPTE_SIZE));
1549                 lbuf = (unsigned long __user *)buf;
1550                 for (j = 0; j < hdr.n_valid; ++j) {
1551                         err = -EFAULT;
1552                         if (__get_user(v, lbuf) || __get_user(r, lbuf + 1))
1553                                 goto out;
1554                         err = -EINVAL;
1555                         if (!(v & HPTE_V_VALID))
1556                                 goto out;
1557                         lbuf += 2;
1558                         nb += HPTE_SIZE;
1559
1560                         if (be64_to_cpu(hptp[0]) & (HPTE_V_VALID | HPTE_V_ABSENT))
1561                                 kvmppc_do_h_remove(kvm, 0, i, 0, tmp);
1562                         err = -EIO;
1563                         ret = kvmppc_virtmode_do_h_enter(kvm, H_EXACT, i, v, r,
1564                                                          tmp);
1565                         if (ret != H_SUCCESS) {
1566                                 pr_err("kvm_htab_write ret %ld i=%ld v=%lx "
1567                                        "r=%lx\n", ret, i, v, r);
1568                                 goto out;
1569                         }
1570                         if (!rma_setup && is_vrma_hpte(v)) {
1571                                 unsigned long psize = hpte_page_size(v, r);
1572                                 unsigned long senc = slb_pgsize_encoding(psize);
1573                                 unsigned long lpcr;
1574
1575                                 kvm->arch.vrma_slb_v = senc | SLB_VSID_B_1T |
1576                                         (VRMA_VSID << SLB_VSID_SHIFT_1T);
1577                                 lpcr = senc << (LPCR_VRMASD_SH - 4);
1578                                 kvmppc_update_lpcr(kvm, lpcr, LPCR_VRMASD);
1579                                 rma_setup = 1;
1580                         }
1581                         ++i;
1582                         hptp += 2;
1583                 }
1584
1585                 for (j = 0; j < hdr.n_invalid; ++j) {
1586                         if (be64_to_cpu(hptp[0]) & (HPTE_V_VALID | HPTE_V_ABSENT))
1587                                 kvmppc_do_h_remove(kvm, 0, i, 0, tmp);
1588                         ++i;
1589                         hptp += 2;
1590                 }
1591                 err = 0;
1592         }
1593
1594  out:
1595         /* Order HPTE updates vs. rma_setup_done */
1596         smp_wmb();
1597         kvm->arch.rma_setup_done = rma_setup;
1598         mutex_unlock(&kvm->lock);
1599
1600         if (err)
1601                 return err;
1602         return nb;
1603 }
1604
1605 static int kvm_htab_release(struct inode *inode, struct file *filp)
1606 {
1607         struct kvm_htab_ctx *ctx = filp->private_data;
1608
1609         filp->private_data = NULL;
1610         if (!(ctx->flags & KVM_GET_HTAB_WRITE))
1611                 atomic_dec(&ctx->kvm->arch.hpte_mod_interest);
1612         kvm_put_kvm(ctx->kvm);
1613         kfree(ctx);
1614         return 0;
1615 }
1616
1617 static const struct file_operations kvm_htab_fops = {
1618         .read           = kvm_htab_read,
1619         .write          = kvm_htab_write,
1620         .llseek         = default_llseek,
1621         .release        = kvm_htab_release,
1622 };
1623
1624 int kvm_vm_ioctl_get_htab_fd(struct kvm *kvm, struct kvm_get_htab_fd *ghf)
1625 {
1626         int ret;
1627         struct kvm_htab_ctx *ctx;
1628         int rwflag;
1629
1630         /* reject flags we don't recognize */
1631         if (ghf->flags & ~(KVM_GET_HTAB_BOLTED_ONLY | KVM_GET_HTAB_WRITE))
1632                 return -EINVAL;
1633         ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1634         if (!ctx)
1635                 return -ENOMEM;
1636         kvm_get_kvm(kvm);
1637         ctx->kvm = kvm;
1638         ctx->index = ghf->start_index;
1639         ctx->flags = ghf->flags;
1640         ctx->first_pass = 1;
1641
1642         rwflag = (ghf->flags & KVM_GET_HTAB_WRITE) ? O_WRONLY : O_RDONLY;
1643         ret = anon_inode_getfd("kvm-htab", &kvm_htab_fops, ctx, rwflag | O_CLOEXEC);
1644         if (ret < 0) {
1645                 kvm_put_kvm(kvm);
1646                 return ret;
1647         }
1648
1649         if (rwflag == O_RDONLY) {
1650                 mutex_lock(&kvm->slots_lock);
1651                 atomic_inc(&kvm->arch.hpte_mod_interest);
1652                 /* make sure kvmppc_do_h_enter etc. see the increment */
1653                 synchronize_srcu_expedited(&kvm->srcu);
1654                 mutex_unlock(&kvm->slots_lock);
1655         }
1656
1657         return ret;
1658 }
1659
1660 void kvmppc_mmu_book3s_hv_init(struct kvm_vcpu *vcpu)
1661 {
1662         struct kvmppc_mmu *mmu = &vcpu->arch.mmu;
1663
1664         if (cpu_has_feature(CPU_FTR_ARCH_206))
1665                 vcpu->arch.slb_nr = 32;         /* POWER7 */
1666         else
1667                 vcpu->arch.slb_nr = 64;
1668
1669         mmu->xlate = kvmppc_mmu_book3s_64_hv_xlate;
1670         mmu->reset_msr = kvmppc_mmu_book3s_64_hv_reset_msr;
1671
1672         vcpu->arch.hflags |= BOOK3S_HFLAG_SLB;
1673 }