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