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