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