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