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