xref: /linux/arch/powerpc/kvm/book3s_64_mmu_hv.c (revision 4e6e66ecf62185828f731914000a6b0baff355db)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  *
4  * Copyright 2010 Paul Mackerras, IBM Corp. <paulus@au1.ibm.com>
5  */
6 
7 #include <linux/types.h>
8 #include <linux/string.h>
9 #include <linux/kvm.h>
10 #include <linux/kvm_host.h>
11 #include <linux/highmem.h>
12 #include <linux/gfp.h>
13 #include <linux/slab.h>
14 #include <linux/hugetlb.h>
15 #include <linux/vmalloc.h>
16 #include <linux/srcu.h>
17 #include <linux/anon_inodes.h>
18 #include <linux/file.h>
19 #include <linux/debugfs.h>
20 
21 #include <asm/kvm_ppc.h>
22 #include <asm/kvm_book3s.h>
23 #include <asm/book3s/64/mmu-hash.h>
24 #include <asm/hvcall.h>
25 #include <asm/synch.h>
26 #include <asm/ppc-opcode.h>
27 #include <asm/cputable.h>
28 #include <asm/pte-walk.h>
29 
30 #include "book3s.h"
31 #include "book3s_hv.h"
32 #include "trace_hv.h"
33 
34 //#define DEBUG_RESIZE_HPT	1
35 
36 #ifdef DEBUG_RESIZE_HPT
37 #define resize_hpt_debug(resize, ...)				\
38 	do {							\
39 		printk(KERN_DEBUG "RESIZE HPT %p: ", resize);	\
40 		printk(__VA_ARGS__);				\
41 	} while (0)
42 #else
43 #define resize_hpt_debug(resize, ...)				\
44 	do { } while (0)
45 #endif
46 
47 static long kvmppc_virtmode_do_h_enter(struct kvm *kvm, unsigned long flags,
48 				long pte_index, unsigned long pteh,
49 				unsigned long ptel, unsigned long *pte_idx_ret);
50 static void kvmppc_virtmode_do_h_remove(struct kvm *kvm, unsigned long flags,
51 				unsigned long pte_index, unsigned long avpn,
52 				unsigned long *hpret);
53 
54 struct kvm_resize_hpt {
55 	/* These fields read-only after init */
56 	struct kvm *kvm;
57 	struct work_struct work;
58 	u32 order;
59 
60 	/* These fields protected by kvm->arch.mmu_setup_lock */
61 
62 	/* Possible values and their usage:
63 	 *  <0     an error occurred during allocation,
64 	 *  -EBUSY allocation is in the progress,
65 	 *  0      allocation made successfully.
66 	 */
67 	int error;
68 
69 	/* Private to the work thread, until error != -EBUSY,
70 	 * then protected by kvm->arch.mmu_setup_lock.
71 	 */
72 	struct kvm_hpt_info hpt;
73 };
74 
75 int kvmppc_allocate_hpt(struct kvm_hpt_info *info, u32 order)
76 {
77 	unsigned long hpt = 0;
78 	int cma = 0;
79 	struct page *page = NULL;
80 	struct revmap_entry *rev;
81 	unsigned long npte;
82 
83 	if ((order < PPC_MIN_HPT_ORDER) || (order > PPC_MAX_HPT_ORDER))
84 		return -EINVAL;
85 
86 	page = kvm_alloc_hpt_cma(1ul << (order - PAGE_SHIFT));
87 	if (page) {
88 		hpt = (unsigned long)pfn_to_kaddr(page_to_pfn(page));
89 		memset((void *)hpt, 0, (1ul << order));
90 		cma = 1;
91 	}
92 
93 	if (!hpt)
94 		hpt = __get_free_pages(GFP_KERNEL|__GFP_ZERO|__GFP_RETRY_MAYFAIL
95 				       |__GFP_NOWARN, order - PAGE_SHIFT);
96 
97 	if (!hpt)
98 		return -ENOMEM;
99 
100 	/* HPTEs are 2**4 bytes long */
101 	npte = 1ul << (order - 4);
102 
103 	/* Allocate reverse map array */
104 	rev = vmalloc(array_size(npte, sizeof(struct revmap_entry)));
105 	if (!rev) {
106 		if (cma)
107 			kvm_free_hpt_cma(page, 1 << (order - PAGE_SHIFT));
108 		else
109 			free_pages(hpt, order - PAGE_SHIFT);
110 		return -ENOMEM;
111 	}
112 
113 	info->order = order;
114 	info->virt = hpt;
115 	info->cma = cma;
116 	info->rev = rev;
117 
118 	return 0;
119 }
120 
121 void kvmppc_set_hpt(struct kvm *kvm, struct kvm_hpt_info *info)
122 {
123 	atomic64_set(&kvm->arch.mmio_update, 0);
124 	kvm->arch.hpt = *info;
125 	kvm->arch.sdr1 = __pa(info->virt) | (info->order - 18);
126 
127 	pr_debug("KVM guest htab at %lx (order %ld), LPID %llx\n",
128 		 info->virt, (long)info->order, kvm->arch.lpid);
129 }
130 
131 int kvmppc_alloc_reset_hpt(struct kvm *kvm, int order)
132 {
133 	int err = -EBUSY;
134 	struct kvm_hpt_info info;
135 
136 	mutex_lock(&kvm->arch.mmu_setup_lock);
137 	if (kvm->arch.mmu_ready) {
138 		kvm->arch.mmu_ready = 0;
139 		/* order mmu_ready vs. vcpus_running */
140 		smp_mb();
141 		if (atomic_read(&kvm->arch.vcpus_running)) {
142 			kvm->arch.mmu_ready = 1;
143 			goto out;
144 		}
145 	}
146 	if (kvm_is_radix(kvm)) {
147 		err = kvmppc_switch_mmu_to_hpt(kvm);
148 		if (err)
149 			goto out;
150 	}
151 
152 	if (kvm->arch.hpt.order == order) {
153 		/* We already have a suitable HPT */
154 
155 		/* Set the entire HPT to 0, i.e. invalid HPTEs */
156 		memset((void *)kvm->arch.hpt.virt, 0, 1ul << order);
157 		/*
158 		 * Reset all the reverse-mapping chains for all memslots
159 		 */
160 		kvmppc_rmap_reset(kvm);
161 		err = 0;
162 		goto out;
163 	}
164 
165 	if (kvm->arch.hpt.virt) {
166 		kvmppc_free_hpt(&kvm->arch.hpt);
167 		kvmppc_rmap_reset(kvm);
168 	}
169 
170 	err = kvmppc_allocate_hpt(&info, order);
171 	if (err < 0)
172 		goto out;
173 	kvmppc_set_hpt(kvm, &info);
174 
175 out:
176 	if (err == 0)
177 		/* Ensure that each vcpu will flush its TLB on next entry. */
178 		cpumask_setall(&kvm->arch.need_tlb_flush);
179 
180 	mutex_unlock(&kvm->arch.mmu_setup_lock);
181 	return err;
182 }
183 
184 void kvmppc_free_hpt(struct kvm_hpt_info *info)
185 {
186 	vfree(info->rev);
187 	info->rev = NULL;
188 	if (info->cma)
189 		kvm_free_hpt_cma(virt_to_page((void *)info->virt),
190 				 1 << (info->order - PAGE_SHIFT));
191 	else if (info->virt)
192 		free_pages(info->virt, info->order - PAGE_SHIFT);
193 	info->virt = 0;
194 	info->order = 0;
195 }
196 
197 /* Bits in first HPTE dword for pagesize 4k, 64k or 16M */
198 static inline unsigned long hpte0_pgsize_encoding(unsigned long pgsize)
199 {
200 	return (pgsize > 0x1000) ? HPTE_V_LARGE : 0;
201 }
202 
203 /* Bits in second HPTE dword for pagesize 4k, 64k or 16M */
204 static inline unsigned long hpte1_pgsize_encoding(unsigned long pgsize)
205 {
206 	return (pgsize == 0x10000) ? 0x1000 : 0;
207 }
208 
209 void kvmppc_map_vrma(struct kvm_vcpu *vcpu, struct kvm_memory_slot *memslot,
210 		     unsigned long porder)
211 {
212 	unsigned long i;
213 	unsigned long npages;
214 	unsigned long hp_v, hp_r;
215 	unsigned long addr, hash;
216 	unsigned long psize;
217 	unsigned long hp0, hp1;
218 	unsigned long idx_ret;
219 	long ret;
220 	struct kvm *kvm = vcpu->kvm;
221 
222 	psize = 1ul << porder;
223 	npages = memslot->npages >> (porder - PAGE_SHIFT);
224 
225 	/* VRMA can't be > 1TB */
226 	if (npages > 1ul << (40 - porder))
227 		npages = 1ul << (40 - porder);
228 	/* Can't use more than 1 HPTE per HPTEG */
229 	if (npages > kvmppc_hpt_mask(&kvm->arch.hpt) + 1)
230 		npages = kvmppc_hpt_mask(&kvm->arch.hpt) + 1;
231 
232 	hp0 = HPTE_V_1TB_SEG | (VRMA_VSID << (40 - 16)) |
233 		HPTE_V_BOLTED | hpte0_pgsize_encoding(psize);
234 	hp1 = hpte1_pgsize_encoding(psize) |
235 		HPTE_R_R | HPTE_R_C | HPTE_R_M | PP_RWXX;
236 
237 	for (i = 0; i < npages; ++i) {
238 		addr = i << porder;
239 		/* can't use hpt_hash since va > 64 bits */
240 		hash = (i ^ (VRMA_VSID ^ (VRMA_VSID << 25)))
241 			& kvmppc_hpt_mask(&kvm->arch.hpt);
242 		/*
243 		 * We assume that the hash table is empty and no
244 		 * vcpus are using it at this stage.  Since we create
245 		 * at most one HPTE per HPTEG, we just assume entry 7
246 		 * is available and use it.
247 		 */
248 		hash = (hash << 3) + 7;
249 		hp_v = hp0 | ((addr >> 16) & ~0x7fUL);
250 		hp_r = hp1 | addr;
251 		ret = kvmppc_virtmode_do_h_enter(kvm, H_EXACT, hash, hp_v, hp_r,
252 						 &idx_ret);
253 		if (ret != H_SUCCESS) {
254 			pr_err("KVM: map_vrma at %lx failed, ret=%ld\n",
255 			       addr, ret);
256 			break;
257 		}
258 	}
259 }
260 
261 int kvmppc_mmu_hv_init(void)
262 {
263 	unsigned long nr_lpids;
264 
265 	if (!mmu_has_feature(MMU_FTR_LOCKLESS_TLBIE))
266 		return -EINVAL;
267 
268 	if (cpu_has_feature(CPU_FTR_HVMODE)) {
269 		if (WARN_ON(mfspr(SPRN_LPID) != 0))
270 			return -EINVAL;
271 		nr_lpids = 1UL << mmu_lpid_bits;
272 	} else {
273 		nr_lpids = 1UL << KVM_MAX_NESTED_GUESTS_SHIFT;
274 	}
275 
276 	if (!cpu_has_feature(CPU_FTR_ARCH_300)) {
277 		/* POWER7 has 10-bit LPIDs, POWER8 has 12-bit LPIDs */
278 		if (cpu_has_feature(CPU_FTR_ARCH_207S))
279 			WARN_ON(nr_lpids != 1UL << 12);
280 		else
281 			WARN_ON(nr_lpids != 1UL << 10);
282 
283 		/*
284 		 * Reserve the last implemented LPID use in partition
285 		 * switching for POWER7 and POWER8.
286 		 */
287 		nr_lpids -= 1;
288 	}
289 
290 	kvmppc_init_lpid(nr_lpids);
291 
292 	return 0;
293 }
294 
295 static long kvmppc_virtmode_do_h_enter(struct kvm *kvm, unsigned long flags,
296 				long pte_index, unsigned long pteh,
297 				unsigned long ptel, unsigned long *pte_idx_ret)
298 {
299 	long ret;
300 
301 	preempt_disable();
302 	ret = kvmppc_do_h_enter(kvm, flags, pte_index, pteh, ptel,
303 				kvm->mm->pgd, false, pte_idx_ret);
304 	preempt_enable();
305 	if (ret == H_TOO_HARD) {
306 		/* this can't happen */
307 		pr_err("KVM: Oops, kvmppc_h_enter returned too hard!\n");
308 		ret = H_RESOURCE;	/* or something */
309 	}
310 	return ret;
311 
312 }
313 
314 /*
315  * Virtual-mode H_REMOVE. kvmppc_do_h_remove() is also called from real mode,
316  * where preempt_disable() is not usable, so the guard stays here. The function
317  * spins on HPTE_V_HVLOCK and then lock_rmap() (via remove_revmap_chain());
318  * preemption must be disabled across both bit-locks so that spinning callers
319  * holding preempt_disable() can make forward progress.
320  */
321 static void kvmppc_virtmode_do_h_remove(struct kvm *kvm, unsigned long flags,
322 				unsigned long pte_index, unsigned long avpn,
323 				unsigned long *hpret)
324 {
325 	preempt_disable();
326 	kvmppc_do_h_remove(kvm, flags, pte_index, avpn, hpret);
327 	preempt_enable();
328 }
329 
330 static struct kvmppc_slb *kvmppc_mmu_book3s_hv_find_slbe(struct kvm_vcpu *vcpu,
331 							 gva_t eaddr)
332 {
333 	u64 mask;
334 	int i;
335 
336 	for (i = 0; i < vcpu->arch.slb_nr; i++) {
337 		if (!(vcpu->arch.slb[i].orige & SLB_ESID_V))
338 			continue;
339 
340 		if (vcpu->arch.slb[i].origv & SLB_VSID_B_1T)
341 			mask = ESID_MASK_1T;
342 		else
343 			mask = ESID_MASK;
344 
345 		if (((vcpu->arch.slb[i].orige ^ eaddr) & mask) == 0)
346 			return &vcpu->arch.slb[i];
347 	}
348 	return NULL;
349 }
350 
351 static unsigned long kvmppc_mmu_get_real_addr(unsigned long v, unsigned long r,
352 			unsigned long ea)
353 {
354 	unsigned long ra_mask;
355 
356 	ra_mask = kvmppc_actual_pgsz(v, r) - 1;
357 	return (r & HPTE_R_RPN & ~ra_mask) | (ea & ra_mask);
358 }
359 
360 static int kvmppc_mmu_book3s_64_hv_xlate(struct kvm_vcpu *vcpu, gva_t eaddr,
361 			struct kvmppc_pte *gpte, bool data, bool iswrite)
362 {
363 	struct kvm *kvm = vcpu->kvm;
364 	struct kvmppc_slb *slbe;
365 	unsigned long slb_v;
366 	unsigned long pp, key;
367 	unsigned long v, orig_v, gr;
368 	__be64 *hptep;
369 	long int index;
370 	int virtmode = __kvmppc_get_msr_hv(vcpu) & (data ? MSR_DR : MSR_IR);
371 
372 	if (kvm_is_radix(vcpu->kvm))
373 		return kvmppc_mmu_radix_xlate(vcpu, eaddr, gpte, data, iswrite);
374 
375 	/* Get SLB entry */
376 	if (virtmode) {
377 		slbe = kvmppc_mmu_book3s_hv_find_slbe(vcpu, eaddr);
378 		if (!slbe)
379 			return -EINVAL;
380 		slb_v = slbe->origv;
381 	} else {
382 		/* real mode access */
383 		slb_v = vcpu->kvm->arch.vrma_slb_v;
384 	}
385 
386 	preempt_disable();
387 	/* Find the HPTE in the hash table */
388 	index = kvmppc_hv_find_lock_hpte(kvm, eaddr, slb_v,
389 					 HPTE_V_VALID | HPTE_V_ABSENT);
390 	if (index < 0) {
391 		preempt_enable();
392 		return -ENOENT;
393 	}
394 	hptep = (__be64 *)(kvm->arch.hpt.virt + (index << 4));
395 	v = orig_v = be64_to_cpu(hptep[0]) & ~HPTE_V_HVLOCK;
396 	if (cpu_has_feature(CPU_FTR_ARCH_300))
397 		v = hpte_new_to_old_v(v, be64_to_cpu(hptep[1]));
398 	gr = kvm->arch.hpt.rev[index].guest_rpte;
399 
400 	unlock_hpte(hptep, orig_v);
401 	preempt_enable();
402 
403 	gpte->eaddr = eaddr;
404 	gpte->vpage = ((v & HPTE_V_AVPN) << 4) | ((eaddr >> 12) & 0xfff);
405 
406 	/* Get PP bits and key for permission check */
407 	pp = gr & (HPTE_R_PP0 | HPTE_R_PP);
408 	key = (__kvmppc_get_msr_hv(vcpu) & MSR_PR) ? SLB_VSID_KP : SLB_VSID_KS;
409 	key &= slb_v;
410 
411 	/* Calculate permissions */
412 	gpte->may_read = hpte_read_permission(pp, key);
413 	gpte->may_write = hpte_write_permission(pp, key);
414 	gpte->may_execute = gpte->may_read && !(gr & (HPTE_R_N | HPTE_R_G));
415 
416 	/* Storage key permission check for POWER7 */
417 	if (data && virtmode) {
418 		int amrfield = hpte_get_skey_perm(gr, vcpu->arch.amr);
419 		if (amrfield & 1)
420 			gpte->may_read = 0;
421 		if (amrfield & 2)
422 			gpte->may_write = 0;
423 	}
424 
425 	/* Get the guest physical address */
426 	gpte->raddr = kvmppc_mmu_get_real_addr(v, gr, eaddr);
427 	return 0;
428 }
429 
430 /*
431  * Quick test for whether an instruction is a load or a store.
432  * If the instruction is a load or a store, then this will indicate
433  * which it is, at least on server processors.  (Embedded processors
434  * have some external PID instructions that don't follow the rule
435  * embodied here.)  If the instruction isn't a load or store, then
436  * this doesn't return anything useful.
437  */
438 static int instruction_is_store(ppc_inst_t instr)
439 {
440 	unsigned int mask;
441 	unsigned int suffix;
442 
443 	mask = 0x10000000;
444 	suffix = ppc_inst_val(instr);
445 	if (ppc_inst_prefixed(instr))
446 		suffix = ppc_inst_suffix(instr);
447 	else if ((suffix & 0xfc000000) == 0x7c000000)
448 		mask = 0x100;		/* major opcode 31 */
449 	return (suffix & mask) != 0;
450 }
451 
452 int kvmppc_hv_emulate_mmio(struct kvm_vcpu *vcpu,
453 			   unsigned long gpa, gva_t ea, int is_store)
454 {
455 	ppc_inst_t last_inst;
456 	bool is_prefixed = !!(kvmppc_get_msr(vcpu) & SRR1_PREFIXED);
457 
458 	/*
459 	 * Fast path - check if the guest physical address corresponds to a
460 	 * device on the FAST_MMIO_BUS, if so we can avoid loading the
461 	 * instruction all together, then we can just handle it and return.
462 	 */
463 	if (is_store) {
464 		int idx, ret;
465 
466 		idx = srcu_read_lock(&vcpu->kvm->srcu);
467 		ret = kvm_io_bus_write(vcpu, KVM_FAST_MMIO_BUS, (gpa_t) gpa, 0,
468 				       NULL);
469 		srcu_read_unlock(&vcpu->kvm->srcu, idx);
470 		if (!ret) {
471 			kvmppc_set_pc(vcpu, kvmppc_get_pc(vcpu) + (is_prefixed ? 8 : 4));
472 			return RESUME_GUEST;
473 		}
474 	}
475 
476 	/*
477 	 * If we fail, we just return to the guest and try executing it again.
478 	 */
479 	if (kvmppc_get_last_inst(vcpu, INST_GENERIC, &last_inst) !=
480 		EMULATE_DONE)
481 		return RESUME_GUEST;
482 
483 	/*
484 	 * WARNING: We do not know for sure whether the instruction we just
485 	 * read from memory is the same that caused the fault in the first
486 	 * place.
487 	 *
488 	 * If the fault is prefixed but the instruction is not or vice
489 	 * versa, try again so that we don't advance pc the wrong amount.
490 	 */
491 	if (ppc_inst_prefixed(last_inst) != is_prefixed)
492 		return RESUME_GUEST;
493 
494 	/*
495 	 * If the instruction we read is neither an load or a store,
496 	 * then it can't access memory, so we don't need to worry about
497 	 * enforcing access permissions.  So, assuming it is a load or
498 	 * store, we just check that its direction (load or store) is
499 	 * consistent with the original fault, since that's what we
500 	 * checked the access permissions against.  If there is a mismatch
501 	 * we just return and retry the instruction.
502 	 */
503 
504 	if (instruction_is_store(last_inst) != !!is_store)
505 		return RESUME_GUEST;
506 
507 	/*
508 	 * Emulated accesses are emulated by looking at the hash for
509 	 * translation once, then performing the access later. The
510 	 * translation could be invalidated in the meantime in which
511 	 * point performing the subsequent memory access on the old
512 	 * physical address could possibly be a security hole for the
513 	 * guest (but not the host).
514 	 *
515 	 * This is less of an issue for MMIO stores since they aren't
516 	 * globally visible. It could be an issue for MMIO loads to
517 	 * a certain extent but we'll ignore it for now.
518 	 */
519 
520 	vcpu->arch.paddr_accessed = gpa;
521 	vcpu->arch.vaddr_accessed = ea;
522 	return kvmppc_emulate_mmio(vcpu);
523 }
524 
525 int kvmppc_book3s_hv_page_fault(struct kvm_vcpu *vcpu,
526 				unsigned long ea, unsigned long dsisr)
527 {
528 	struct kvm *kvm = vcpu->kvm;
529 	unsigned long hpte[3], r;
530 	unsigned long hnow_v, hnow_r;
531 	__be64 *hptep;
532 	unsigned long mmu_seq, psize, pte_size;
533 	unsigned long gpa_base, gfn_base;
534 	unsigned long gpa, gfn, hva, pfn, hpa;
535 	struct kvm_memory_slot *memslot;
536 	unsigned long *rmap;
537 	struct revmap_entry *rev;
538 	struct page *page;
539 	long index, ret;
540 	bool is_ci;
541 	bool writing, write_ok;
542 	unsigned int shift;
543 	unsigned long rcbits;
544 	long mmio_update;
545 	pte_t pte, *ptep;
546 
547 	if (kvm_is_radix(kvm))
548 		return kvmppc_book3s_radix_page_fault(vcpu, ea, dsisr);
549 
550 	/*
551 	 * Real-mode code has already searched the HPT and found the
552 	 * entry we're interested in.  Lock the entry and check that
553 	 * it hasn't changed.  If it has, just return and re-execute the
554 	 * instruction.
555 	 */
556 	if (ea != vcpu->arch.pgfault_addr)
557 		return RESUME_GUEST;
558 
559 	if (vcpu->arch.pgfault_cache) {
560 		mmio_update = atomic64_read(&kvm->arch.mmio_update);
561 		if (mmio_update == vcpu->arch.pgfault_cache->mmio_update) {
562 			r = vcpu->arch.pgfault_cache->rpte;
563 			psize = kvmppc_actual_pgsz(vcpu->arch.pgfault_hpte[0],
564 						   r);
565 			gpa_base = r & HPTE_R_RPN & ~(psize - 1);
566 			gfn_base = gpa_base >> PAGE_SHIFT;
567 			gpa = gpa_base | (ea & (psize - 1));
568 			return kvmppc_hv_emulate_mmio(vcpu, gpa, ea,
569 						dsisr & DSISR_ISSTORE);
570 		}
571 	}
572 	index = vcpu->arch.pgfault_index;
573 	hptep = (__be64 *)(kvm->arch.hpt.virt + (index << 4));
574 	rev = &kvm->arch.hpt.rev[index];
575 	preempt_disable();
576 	while (!try_lock_hpte(hptep, HPTE_V_HVLOCK))
577 		cpu_relax();
578 	hpte[0] = be64_to_cpu(hptep[0]) & ~HPTE_V_HVLOCK;
579 	hpte[1] = be64_to_cpu(hptep[1]);
580 	hpte[2] = r = rev->guest_rpte;
581 	unlock_hpte(hptep, hpte[0]);
582 	preempt_enable();
583 
584 	if (cpu_has_feature(CPU_FTR_ARCH_300)) {
585 		hpte[0] = hpte_new_to_old_v(hpte[0], hpte[1]);
586 		hpte[1] = hpte_new_to_old_r(hpte[1]);
587 	}
588 	if (hpte[0] != vcpu->arch.pgfault_hpte[0] ||
589 	    hpte[1] != vcpu->arch.pgfault_hpte[1])
590 		return RESUME_GUEST;
591 
592 	/* Translate the logical address and get the page */
593 	psize = kvmppc_actual_pgsz(hpte[0], r);
594 	gpa_base = r & HPTE_R_RPN & ~(psize - 1);
595 	gfn_base = gpa_base >> PAGE_SHIFT;
596 	gpa = gpa_base | (ea & (psize - 1));
597 	gfn = gpa >> PAGE_SHIFT;
598 	memslot = gfn_to_memslot(kvm, gfn);
599 
600 	trace_kvm_page_fault_enter(vcpu, hpte, memslot, ea, dsisr);
601 
602 	/* No memslot means it's an emulated MMIO region */
603 	if (!memslot || (memslot->flags & KVM_MEMSLOT_INVALID))
604 		return kvmppc_hv_emulate_mmio(vcpu, gpa, ea,
605 					      dsisr & DSISR_ISSTORE);
606 
607 	/*
608 	 * This should never happen, because of the slot_is_aligned()
609 	 * check in kvmppc_do_h_enter().
610 	 */
611 	if (gfn_base < memslot->base_gfn)
612 		return -EFAULT;
613 
614 	/* used to check for invalidations in progress */
615 	mmu_seq = kvm->mmu_invalidate_seq;
616 	smp_rmb();
617 
618 	ret = -EFAULT;
619 	page = NULL;
620 	writing = (dsisr & DSISR_ISSTORE) != 0;
621 	/* If writing != 0, then the HPTE must allow writing, if we get here */
622 	write_ok = writing;
623 	hva = gfn_to_hva_memslot(memslot, gfn);
624 
625 	pfn = __kvm_faultin_pfn(memslot, gfn, writing ? FOLL_WRITE : 0,
626 				&write_ok, &page);
627 	if (is_error_noslot_pfn(pfn))
628 		return -EFAULT;
629 
630 	/*
631 	 * Read the PTE from the process' radix tree and use that
632 	 * so we get the shift and attribute bits.
633 	 */
634 	spin_lock(&kvm->mmu_lock);
635 	ptep = find_kvm_host_pte(kvm, mmu_seq, hva, &shift);
636 	pte = __pte(0);
637 	if (ptep)
638 		pte = READ_ONCE(*ptep);
639 	spin_unlock(&kvm->mmu_lock);
640 	/*
641 	 * If the PTE disappeared temporarily due to a THP
642 	 * collapse, just return and let the guest try again.
643 	 */
644 	if (!pte_present(pte)) {
645 		if (page)
646 			put_page(page);
647 		return RESUME_GUEST;
648 	}
649 	hpa = pte_pfn(pte) << PAGE_SHIFT;
650 	pte_size = PAGE_SIZE;
651 	if (shift)
652 		pte_size = 1ul << shift;
653 	is_ci = pte_ci(pte);
654 
655 	if (psize > pte_size)
656 		goto out_put;
657 	if (pte_size > psize)
658 		hpa |= hva & (pte_size - psize);
659 
660 	/* Check WIMG vs. the actual page we're accessing */
661 	if (!hpte_cache_flags_ok(r, is_ci)) {
662 		if (is_ci)
663 			goto out_put;
664 		/*
665 		 * Allow guest to map emulated device memory as
666 		 * uncacheable, but actually make it cacheable.
667 		 */
668 		r = (r & ~(HPTE_R_W|HPTE_R_I|HPTE_R_G)) | HPTE_R_M;
669 	}
670 
671 	/*
672 	 * Set the HPTE to point to hpa.
673 	 * Since the hpa is at PAGE_SIZE granularity, make sure we
674 	 * don't mask out lower-order bits if psize < PAGE_SIZE.
675 	 */
676 	if (psize < PAGE_SIZE)
677 		psize = PAGE_SIZE;
678 	r = (r & HPTE_R_KEY_HI) | (r & ~(HPTE_R_PP0 - psize)) | hpa;
679 	if (hpte_is_writable(r) && !write_ok)
680 		r = hpte_make_readonly(r);
681 	ret = RESUME_GUEST;
682 	preempt_disable();
683 	while (!try_lock_hpte(hptep, HPTE_V_HVLOCK))
684 		cpu_relax();
685 	hnow_v = be64_to_cpu(hptep[0]);
686 	hnow_r = be64_to_cpu(hptep[1]);
687 	if (cpu_has_feature(CPU_FTR_ARCH_300)) {
688 		hnow_v = hpte_new_to_old_v(hnow_v, hnow_r);
689 		hnow_r = hpte_new_to_old_r(hnow_r);
690 	}
691 
692 	/*
693 	 * If the HPT is being resized, don't update the HPTE,
694 	 * instead let the guest retry after the resize operation is complete.
695 	 * The synchronization for mmu_ready test vs. set is provided
696 	 * by the HPTE lock.
697 	 */
698 	if (!kvm->arch.mmu_ready)
699 		goto out_unlock;
700 
701 	if ((hnow_v & ~HPTE_V_HVLOCK) != hpte[0] || hnow_r != hpte[1] ||
702 	    rev->guest_rpte != hpte[2])
703 		/* HPTE has been changed under us; let the guest retry */
704 		goto out_unlock;
705 	hpte[0] = (hpte[0] & ~HPTE_V_ABSENT) | HPTE_V_VALID;
706 
707 	/* Always put the HPTE in the rmap chain for the page base address */
708 	rmap = &memslot->arch.rmap[gfn_base - memslot->base_gfn];
709 	lock_rmap(rmap);
710 
711 	/* Check if we might have been invalidated; let the guest retry if so */
712 	ret = RESUME_GUEST;
713 	if (mmu_invalidate_retry(vcpu->kvm, mmu_seq)) {
714 		unlock_rmap(rmap);
715 		goto out_unlock;
716 	}
717 
718 	/* Only set R/C in real HPTE if set in both *rmap and guest_rpte */
719 	rcbits = *rmap >> KVMPPC_RMAP_RC_SHIFT;
720 	r &= rcbits | ~(HPTE_R_R | HPTE_R_C);
721 
722 	if (be64_to_cpu(hptep[0]) & HPTE_V_VALID) {
723 		/* HPTE was previously valid, so we need to invalidate it */
724 		unlock_rmap(rmap);
725 		hptep[0] |= cpu_to_be64(HPTE_V_ABSENT);
726 		kvmppc_invalidate_hpte(kvm, hptep, index);
727 		/* don't lose previous R and C bits */
728 		r |= be64_to_cpu(hptep[1]) & (HPTE_R_R | HPTE_R_C);
729 	} else {
730 		kvmppc_add_revmap_chain(kvm, rev, rmap, index, 0);
731 	}
732 
733 	if (cpu_has_feature(CPU_FTR_ARCH_300)) {
734 		r = hpte_old_to_new_r(hpte[0], r);
735 		hpte[0] = hpte_old_to_new_v(hpte[0]);
736 	}
737 	hptep[1] = cpu_to_be64(r);
738 	eieio();
739 	__unlock_hpte(hptep, hpte[0]);
740 	asm volatile("ptesync" : : : "memory");
741 	preempt_enable();
742 	if (page && hpte_is_writable(r))
743 		set_page_dirty_lock(page);
744 
745  out_put:
746 	trace_kvm_page_fault_exit(vcpu, hpte, ret);
747 
748 	if (page)
749 		put_page(page);
750 	return ret;
751 
752  out_unlock:
753 	__unlock_hpte(hptep, be64_to_cpu(hptep[0]));
754 	preempt_enable();
755 	goto out_put;
756 }
757 
758 void kvmppc_rmap_reset(struct kvm *kvm)
759 {
760 	struct kvm_memslots *slots;
761 	struct kvm_memory_slot *memslot;
762 	int srcu_idx, bkt;
763 
764 	srcu_idx = srcu_read_lock(&kvm->srcu);
765 	slots = kvm_memslots(kvm);
766 	kvm_for_each_memslot(memslot, bkt, slots) {
767 		/* Mutual exclusion with kvm_unmap_hva_range etc. */
768 		spin_lock(&kvm->mmu_lock);
769 		/*
770 		 * This assumes it is acceptable to lose reference and
771 		 * change bits across a reset.
772 		 */
773 		memset(memslot->arch.rmap, 0,
774 		       memslot->npages * sizeof(*memslot->arch.rmap));
775 		spin_unlock(&kvm->mmu_lock);
776 	}
777 	srcu_read_unlock(&kvm->srcu, srcu_idx);
778 }
779 
780 /* Must be called with both HPTE and rmap locked */
781 static void kvmppc_unmap_hpte(struct kvm *kvm, unsigned long i,
782 			      struct kvm_memory_slot *memslot,
783 			      unsigned long *rmapp, unsigned long gfn)
784 {
785 	__be64 *hptep = (__be64 *) (kvm->arch.hpt.virt + (i << 4));
786 	struct revmap_entry *rev = kvm->arch.hpt.rev;
787 	unsigned long j, h;
788 	unsigned long ptel, psize, rcbits;
789 
790 	j = rev[i].forw;
791 	if (j == i) {
792 		/* chain is now empty */
793 		*rmapp &= ~(KVMPPC_RMAP_PRESENT | KVMPPC_RMAP_INDEX);
794 	} else {
795 		/* remove i from chain */
796 		h = rev[i].back;
797 		rev[h].forw = j;
798 		rev[j].back = h;
799 		rev[i].forw = rev[i].back = i;
800 		*rmapp = (*rmapp & ~KVMPPC_RMAP_INDEX) | j;
801 	}
802 
803 	/* Now check and modify the HPTE */
804 	ptel = rev[i].guest_rpte;
805 	psize = kvmppc_actual_pgsz(be64_to_cpu(hptep[0]), ptel);
806 	if ((be64_to_cpu(hptep[0]) & HPTE_V_VALID) &&
807 	    hpte_rpn(ptel, psize) == gfn) {
808 		hptep[0] |= cpu_to_be64(HPTE_V_ABSENT);
809 		kvmppc_invalidate_hpte(kvm, hptep, i);
810 		hptep[1] &= ~cpu_to_be64(HPTE_R_KEY_HI | HPTE_R_KEY_LO);
811 		/* Harvest R and C */
812 		rcbits = be64_to_cpu(hptep[1]) & (HPTE_R_R | HPTE_R_C);
813 		*rmapp |= rcbits << KVMPPC_RMAP_RC_SHIFT;
814 		if ((rcbits & HPTE_R_C) && memslot->dirty_bitmap)
815 			kvmppc_update_dirty_map(memslot, gfn, psize);
816 		if (rcbits & ~rev[i].guest_rpte) {
817 			rev[i].guest_rpte = ptel | rcbits;
818 			note_hpte_modification(kvm, &rev[i]);
819 		}
820 	}
821 }
822 
823 static void kvm_unmap_rmapp(struct kvm *kvm, struct kvm_memory_slot *memslot,
824 			    unsigned long gfn)
825 {
826 	unsigned long i;
827 	__be64 *hptep;
828 	unsigned long *rmapp;
829 
830 	rmapp = &memslot->arch.rmap[gfn - memslot->base_gfn];
831 	for (;;) {
832 		preempt_disable();
833 		lock_rmap(rmapp);
834 		if (!(*rmapp & KVMPPC_RMAP_PRESENT)) {
835 			unlock_rmap(rmapp);
836 			preempt_enable();
837 			break;
838 		}
839 
840 		/*
841 		 * To avoid an ABBA deadlock with the HPTE lock bit,
842 		 * we can't spin on the HPTE lock while holding the
843 		 * rmap chain lock.
844 		 */
845 		i = *rmapp & KVMPPC_RMAP_INDEX;
846 		hptep = (__be64 *) (kvm->arch.hpt.virt + (i << 4));
847 		if (!try_lock_hpte(hptep, HPTE_V_HVLOCK)) {
848 			/* unlock rmap before spinning on the HPTE lock */
849 			unlock_rmap(rmapp);
850 			preempt_enable();
851 			while (be64_to_cpu(hptep[0]) & HPTE_V_HVLOCK)
852 				cpu_relax();
853 			continue;
854 		}
855 
856 		kvmppc_unmap_hpte(kvm, i, memslot, rmapp, gfn);
857 		unlock_rmap(rmapp);
858 		__unlock_hpte(hptep, be64_to_cpu(hptep[0]));
859 		preempt_enable();
860 	}
861 }
862 
863 bool kvm_unmap_gfn_range_hv(struct kvm *kvm, struct kvm_gfn_range *range)
864 {
865 	gfn_t gfn;
866 
867 	if (kvm_is_radix(kvm)) {
868 		for (gfn = range->start; gfn < range->end; gfn++)
869 			kvm_unmap_radix(kvm, range->slot, gfn);
870 	} else {
871 		for (gfn = range->start; gfn < range->end; gfn++)
872 			kvm_unmap_rmapp(kvm, range->slot, gfn);
873 	}
874 
875 	return false;
876 }
877 
878 void kvmppc_core_flush_memslot_hv(struct kvm *kvm,
879 				  struct kvm_memory_slot *memslot)
880 {
881 	unsigned long gfn;
882 	unsigned long n;
883 	unsigned long *rmapp;
884 
885 	gfn = memslot->base_gfn;
886 	rmapp = memslot->arch.rmap;
887 	if (kvm_is_radix(kvm)) {
888 		kvmppc_radix_flush_memslot(kvm, memslot);
889 		return;
890 	}
891 
892 	for (n = memslot->npages; n; --n, ++gfn) {
893 		/*
894 		 * Testing the present bit without locking is OK because
895 		 * the memslot has been marked invalid already, and hence
896 		 * no new HPTEs referencing this page can be created,
897 		 * thus the present bit can't go from 0 to 1.
898 		 */
899 		if (*rmapp & KVMPPC_RMAP_PRESENT)
900 			kvm_unmap_rmapp(kvm, memslot, gfn);
901 		++rmapp;
902 	}
903 }
904 
905 static bool kvm_age_rmapp(struct kvm *kvm, struct kvm_memory_slot *memslot,
906 			  unsigned long gfn)
907 {
908 	struct revmap_entry *rev = kvm->arch.hpt.rev;
909 	unsigned long head, i, j;
910 	__be64 *hptep;
911 	bool ret = false;
912 	unsigned long *rmapp;
913 
914 	rmapp = &memslot->arch.rmap[gfn - memslot->base_gfn];
915  retry:
916 	preempt_disable();
917 	lock_rmap(rmapp);
918 	if (*rmapp & KVMPPC_RMAP_REFERENCED) {
919 		*rmapp &= ~KVMPPC_RMAP_REFERENCED;
920 		ret = true;
921 	}
922 	if (!(*rmapp & KVMPPC_RMAP_PRESENT)) {
923 		unlock_rmap(rmapp);
924 		preempt_enable();
925 		return ret;
926 	}
927 
928 	i = head = *rmapp & KVMPPC_RMAP_INDEX;
929 	do {
930 		hptep = (__be64 *) (kvm->arch.hpt.virt + (i << 4));
931 		j = rev[i].forw;
932 
933 		/* If this HPTE isn't referenced, ignore it */
934 		if (!(be64_to_cpu(hptep[1]) & HPTE_R_R))
935 			continue;
936 
937 		if (!try_lock_hpte(hptep, HPTE_V_HVLOCK)) {
938 			/* unlock rmap before spinning on the HPTE lock */
939 			unlock_rmap(rmapp);
940 			preempt_enable();
941 			while (be64_to_cpu(hptep[0]) & HPTE_V_HVLOCK)
942 				cpu_relax();
943 			goto retry;
944 		}
945 
946 		/* Now check and modify the HPTE */
947 		if ((be64_to_cpu(hptep[0]) & HPTE_V_VALID) &&
948 		    (be64_to_cpu(hptep[1]) & HPTE_R_R)) {
949 			kvmppc_clear_ref_hpte(kvm, hptep, i);
950 			if (!(rev[i].guest_rpte & HPTE_R_R)) {
951 				rev[i].guest_rpte |= HPTE_R_R;
952 				note_hpte_modification(kvm, &rev[i]);
953 			}
954 			ret = true;
955 		}
956 		__unlock_hpte(hptep, be64_to_cpu(hptep[0]));
957 	} while ((i = j) != head);
958 
959 	unlock_rmap(rmapp);
960 	preempt_enable();
961 	return ret;
962 }
963 
964 bool kvm_age_gfn_hv(struct kvm *kvm, struct kvm_gfn_range *range)
965 {
966 	gfn_t gfn;
967 	bool ret = false;
968 
969 	if (kvm_is_radix(kvm)) {
970 		for (gfn = range->start; gfn < range->end; gfn++)
971 			ret |= kvm_age_radix(kvm, range->slot, gfn);
972 	} else {
973 		for (gfn = range->start; gfn < range->end; gfn++)
974 			ret |= kvm_age_rmapp(kvm, range->slot, gfn);
975 	}
976 
977 	return ret;
978 }
979 
980 static bool kvm_test_age_rmapp(struct kvm *kvm, struct kvm_memory_slot *memslot,
981 			       unsigned long gfn)
982 {
983 	struct revmap_entry *rev = kvm->arch.hpt.rev;
984 	unsigned long head, i, j;
985 	unsigned long *hp;
986 	bool ret = true;
987 	unsigned long *rmapp;
988 
989 	rmapp = &memslot->arch.rmap[gfn - memslot->base_gfn];
990 	if (*rmapp & KVMPPC_RMAP_REFERENCED)
991 		return true;
992 
993 	lock_rmap(rmapp);
994 	if (*rmapp & KVMPPC_RMAP_REFERENCED)
995 		goto out;
996 
997 	if (*rmapp & KVMPPC_RMAP_PRESENT) {
998 		i = head = *rmapp & KVMPPC_RMAP_INDEX;
999 		do {
1000 			hp = (unsigned long *)(kvm->arch.hpt.virt + (i << 4));
1001 			j = rev[i].forw;
1002 			if (be64_to_cpu(hp[1]) & HPTE_R_R)
1003 				goto out;
1004 		} while ((i = j) != head);
1005 	}
1006 	ret = false;
1007 
1008  out:
1009 	unlock_rmap(rmapp);
1010 	return ret;
1011 }
1012 
1013 bool kvm_test_age_gfn_hv(struct kvm *kvm, struct kvm_gfn_range *range)
1014 {
1015 	WARN_ON(range->start + 1 != range->end);
1016 
1017 	if (kvm_is_radix(kvm))
1018 		return kvm_test_age_radix(kvm, range->slot, range->start);
1019 	else
1020 		return kvm_test_age_rmapp(kvm, range->slot, range->start);
1021 }
1022 
1023 static int vcpus_running(struct kvm *kvm)
1024 {
1025 	return atomic_read(&kvm->arch.vcpus_running) != 0;
1026 }
1027 
1028 /*
1029  * Returns the number of system pages that are dirty.
1030  * This can be more than 1 if we find a huge-page HPTE.
1031  */
1032 static int kvm_test_clear_dirty_npages(struct kvm *kvm, unsigned long *rmapp)
1033 {
1034 	struct revmap_entry *rev = kvm->arch.hpt.rev;
1035 	unsigned long head, i, j;
1036 	unsigned long n;
1037 	unsigned long v, r;
1038 	__be64 *hptep;
1039 	int npages_dirty = 0;
1040 
1041  retry:
1042 	lock_rmap(rmapp);
1043 	if (!(*rmapp & KVMPPC_RMAP_PRESENT)) {
1044 		unlock_rmap(rmapp);
1045 		return npages_dirty;
1046 	}
1047 
1048 	i = head = *rmapp & KVMPPC_RMAP_INDEX;
1049 	do {
1050 		unsigned long hptep1;
1051 		hptep = (__be64 *) (kvm->arch.hpt.virt + (i << 4));
1052 		j = rev[i].forw;
1053 
1054 		/*
1055 		 * Checking the C (changed) bit here is racy since there
1056 		 * is no guarantee about when the hardware writes it back.
1057 		 * If the HPTE is not writable then it is stable since the
1058 		 * page can't be written to, and we would have done a tlbie
1059 		 * (which forces the hardware to complete any writeback)
1060 		 * when making the HPTE read-only.
1061 		 * If vcpus are running then this call is racy anyway
1062 		 * since the page could get dirtied subsequently, so we
1063 		 * expect there to be a further call which would pick up
1064 		 * any delayed C bit writeback.
1065 		 * Otherwise we need to do the tlbie even if C==0 in
1066 		 * order to pick up any delayed writeback of C.
1067 		 */
1068 		hptep1 = be64_to_cpu(hptep[1]);
1069 		if (!(hptep1 & HPTE_R_C) &&
1070 		    (!hpte_is_writable(hptep1) || vcpus_running(kvm)))
1071 			continue;
1072 
1073 		if (!try_lock_hpte(hptep, HPTE_V_HVLOCK)) {
1074 			/* unlock rmap before spinning on the HPTE lock */
1075 			unlock_rmap(rmapp);
1076 			while (hptep[0] & cpu_to_be64(HPTE_V_HVLOCK))
1077 				cpu_relax();
1078 			goto retry;
1079 		}
1080 
1081 		/* Now check and modify the HPTE */
1082 		if (!(hptep[0] & cpu_to_be64(HPTE_V_VALID))) {
1083 			__unlock_hpte(hptep, be64_to_cpu(hptep[0]));
1084 			continue;
1085 		}
1086 
1087 		/* need to make it temporarily absent so C is stable */
1088 		hptep[0] |= cpu_to_be64(HPTE_V_ABSENT);
1089 		kvmppc_invalidate_hpte(kvm, hptep, i);
1090 		v = be64_to_cpu(hptep[0]);
1091 		r = be64_to_cpu(hptep[1]);
1092 		if (r & HPTE_R_C) {
1093 			hptep[1] = cpu_to_be64(r & ~HPTE_R_C);
1094 			if (!(rev[i].guest_rpte & HPTE_R_C)) {
1095 				rev[i].guest_rpte |= HPTE_R_C;
1096 				note_hpte_modification(kvm, &rev[i]);
1097 			}
1098 			n = kvmppc_actual_pgsz(v, r);
1099 			n = (n + PAGE_SIZE - 1) >> PAGE_SHIFT;
1100 			if (n > npages_dirty)
1101 				npages_dirty = n;
1102 			eieio();
1103 		}
1104 		v &= ~HPTE_V_ABSENT;
1105 		v |= HPTE_V_VALID;
1106 		__unlock_hpte(hptep, v);
1107 	} while ((i = j) != head);
1108 
1109 	unlock_rmap(rmapp);
1110 	return npages_dirty;
1111 }
1112 
1113 void kvmppc_harvest_vpa_dirty(struct kvmppc_vpa *vpa,
1114 			      struct kvm_memory_slot *memslot,
1115 			      unsigned long *map)
1116 {
1117 	unsigned long gfn;
1118 
1119 	if (!vpa->dirty || !vpa->pinned_addr)
1120 		return;
1121 	gfn = vpa->gpa >> PAGE_SHIFT;
1122 	if (gfn < memslot->base_gfn ||
1123 	    gfn >= memslot->base_gfn + memslot->npages)
1124 		return;
1125 
1126 	vpa->dirty = false;
1127 	if (map)
1128 		__set_bit_le(gfn - memslot->base_gfn, map);
1129 }
1130 
1131 long kvmppc_hv_get_dirty_log_hpt(struct kvm *kvm,
1132 			struct kvm_memory_slot *memslot, unsigned long *map)
1133 {
1134 	unsigned long i;
1135 	unsigned long *rmapp;
1136 
1137 	preempt_disable();
1138 	rmapp = memslot->arch.rmap;
1139 	for (i = 0; i < memslot->npages; ++i) {
1140 		int npages = kvm_test_clear_dirty_npages(kvm, rmapp);
1141 		/*
1142 		 * Note that if npages > 0 then i must be a multiple of npages,
1143 		 * since we always put huge-page HPTEs in the rmap chain
1144 		 * corresponding to their page base address.
1145 		 */
1146 		if (npages)
1147 			set_dirty_bits(map, i, npages);
1148 		++rmapp;
1149 	}
1150 	preempt_enable();
1151 	return 0;
1152 }
1153 
1154 void *kvmppc_pin_guest_page(struct kvm *kvm, unsigned long gpa,
1155 			    unsigned long *nb_ret)
1156 {
1157 	struct kvm_memory_slot *memslot;
1158 	unsigned long gfn = gpa >> PAGE_SHIFT;
1159 	struct page *page, *pages[1];
1160 	int npages;
1161 	unsigned long hva, offset;
1162 	int srcu_idx;
1163 
1164 	srcu_idx = srcu_read_lock(&kvm->srcu);
1165 	memslot = gfn_to_memslot(kvm, gfn);
1166 	if (!memslot || (memslot->flags & KVM_MEMSLOT_INVALID))
1167 		goto err;
1168 	hva = gfn_to_hva_memslot(memslot, gfn);
1169 	npages = get_user_pages_fast(hva, 1, FOLL_WRITE, pages);
1170 	if (npages < 1)
1171 		goto err;
1172 	page = pages[0];
1173 	srcu_read_unlock(&kvm->srcu, srcu_idx);
1174 
1175 	offset = gpa & (PAGE_SIZE - 1);
1176 	if (nb_ret)
1177 		*nb_ret = PAGE_SIZE - offset;
1178 	return page_address(page) + offset;
1179 
1180  err:
1181 	srcu_read_unlock(&kvm->srcu, srcu_idx);
1182 	return NULL;
1183 }
1184 
1185 void kvmppc_unpin_guest_page(struct kvm *kvm, void *va, unsigned long gpa,
1186 			     bool dirty)
1187 {
1188 	struct page *page = virt_to_page(va);
1189 	struct kvm_memory_slot *memslot;
1190 	unsigned long gfn;
1191 	int srcu_idx;
1192 
1193 	put_page(page);
1194 
1195 	if (!dirty)
1196 		return;
1197 
1198 	/* We need to mark this page dirty in the memslot dirty_bitmap, if any */
1199 	gfn = gpa >> PAGE_SHIFT;
1200 	srcu_idx = srcu_read_lock(&kvm->srcu);
1201 	memslot = gfn_to_memslot(kvm, gfn);
1202 	if (memslot && memslot->dirty_bitmap)
1203 		set_bit_le(gfn - memslot->base_gfn, memslot->dirty_bitmap);
1204 	srcu_read_unlock(&kvm->srcu, srcu_idx);
1205 }
1206 
1207 /*
1208  * HPT resizing
1209  */
1210 static int resize_hpt_allocate(struct kvm_resize_hpt *resize)
1211 {
1212 	int rc;
1213 
1214 	rc = kvmppc_allocate_hpt(&resize->hpt, resize->order);
1215 	if (rc < 0)
1216 		return rc;
1217 
1218 	resize_hpt_debug(resize, "%s(): HPT @ 0x%lx\n", __func__,
1219 			 resize->hpt.virt);
1220 
1221 	return 0;
1222 }
1223 
1224 static unsigned long resize_hpt_rehash_hpte(struct kvm_resize_hpt *resize,
1225 					    unsigned long idx)
1226 {
1227 	struct kvm *kvm = resize->kvm;
1228 	struct kvm_hpt_info *old = &kvm->arch.hpt;
1229 	struct kvm_hpt_info *new = &resize->hpt;
1230 	unsigned long old_hash_mask = (1ULL << (old->order - 7)) - 1;
1231 	unsigned long new_hash_mask = (1ULL << (new->order - 7)) - 1;
1232 	__be64 *hptep, *new_hptep;
1233 	unsigned long vpte, rpte, guest_rpte;
1234 	int ret;
1235 	struct revmap_entry *rev;
1236 	unsigned long apsize, avpn, pteg, hash;
1237 	unsigned long new_idx, new_pteg, replace_vpte;
1238 	int pshift;
1239 
1240 	hptep = (__be64 *)(old->virt + (idx << 4));
1241 
1242 	/* Guest is stopped, so new HPTEs can't be added or faulted
1243 	 * in, only unmapped or altered by host actions.  So, it's
1244 	 * safe to check this before we take the HPTE lock */
1245 	vpte = be64_to_cpu(hptep[0]);
1246 	if (!(vpte & HPTE_V_VALID) && !(vpte & HPTE_V_ABSENT))
1247 		return 0; /* nothing to do */
1248 
1249 	preempt_disable();
1250 	while (!try_lock_hpte(hptep, HPTE_V_HVLOCK))
1251 		cpu_relax();
1252 
1253 	vpte = be64_to_cpu(hptep[0]);
1254 
1255 	ret = 0;
1256 	if (!(vpte & HPTE_V_VALID) && !(vpte & HPTE_V_ABSENT))
1257 		/* Nothing to do */
1258 		goto out;
1259 
1260 	if (cpu_has_feature(CPU_FTR_ARCH_300)) {
1261 		rpte = be64_to_cpu(hptep[1]);
1262 		vpte = hpte_new_to_old_v(vpte, rpte);
1263 	}
1264 
1265 	/* Unmap */
1266 	rev = &old->rev[idx];
1267 	guest_rpte = rev->guest_rpte;
1268 
1269 	ret = -EIO;
1270 	apsize = kvmppc_actual_pgsz(vpte, guest_rpte);
1271 	if (!apsize)
1272 		goto out;
1273 
1274 	if (vpte & HPTE_V_VALID) {
1275 		unsigned long gfn = hpte_rpn(guest_rpte, apsize);
1276 		int srcu_idx = srcu_read_lock(&kvm->srcu);
1277 		struct kvm_memory_slot *memslot =
1278 			__gfn_to_memslot(kvm_memslots(kvm), gfn);
1279 
1280 		if (memslot) {
1281 			unsigned long *rmapp;
1282 			rmapp = &memslot->arch.rmap[gfn - memslot->base_gfn];
1283 
1284 			lock_rmap(rmapp);
1285 			kvmppc_unmap_hpte(kvm, idx, memslot, rmapp, gfn);
1286 			unlock_rmap(rmapp);
1287 		}
1288 
1289 		srcu_read_unlock(&kvm->srcu, srcu_idx);
1290 	}
1291 
1292 	/* Reload PTE after unmap */
1293 	vpte = be64_to_cpu(hptep[0]);
1294 	BUG_ON(vpte & HPTE_V_VALID);
1295 	BUG_ON(!(vpte & HPTE_V_ABSENT));
1296 
1297 	ret = 0;
1298 	if (!(vpte & HPTE_V_BOLTED))
1299 		goto out;
1300 
1301 	rpte = be64_to_cpu(hptep[1]);
1302 
1303 	if (cpu_has_feature(CPU_FTR_ARCH_300)) {
1304 		vpte = hpte_new_to_old_v(vpte, rpte);
1305 		rpte = hpte_new_to_old_r(rpte);
1306 	}
1307 
1308 	pshift = kvmppc_hpte_base_page_shift(vpte, rpte);
1309 	avpn = HPTE_V_AVPN_VAL(vpte) & ~(((1ul << pshift) - 1) >> 23);
1310 	pteg = idx / HPTES_PER_GROUP;
1311 	if (vpte & HPTE_V_SECONDARY)
1312 		pteg = ~pteg;
1313 
1314 	if (!(vpte & HPTE_V_1TB_SEG)) {
1315 		unsigned long offset, vsid;
1316 
1317 		/* We only have 28 - 23 bits of offset in avpn */
1318 		offset = (avpn & 0x1f) << 23;
1319 		vsid = avpn >> 5;
1320 		/* We can find more bits from the pteg value */
1321 		if (pshift < 23)
1322 			offset |= ((vsid ^ pteg) & old_hash_mask) << pshift;
1323 
1324 		hash = vsid ^ (offset >> pshift);
1325 	} else {
1326 		unsigned long offset, vsid;
1327 
1328 		/* We only have 40 - 23 bits of seg_off in avpn */
1329 		offset = (avpn & 0x1ffff) << 23;
1330 		vsid = avpn >> 17;
1331 		if (pshift < 23)
1332 			offset |= ((vsid ^ (vsid << 25) ^ pteg) & old_hash_mask) << pshift;
1333 
1334 		hash = vsid ^ (vsid << 25) ^ (offset >> pshift);
1335 	}
1336 
1337 	new_pteg = hash & new_hash_mask;
1338 	if (vpte & HPTE_V_SECONDARY)
1339 		new_pteg = ~hash & new_hash_mask;
1340 
1341 	new_idx = new_pteg * HPTES_PER_GROUP + (idx % HPTES_PER_GROUP);
1342 	new_hptep = (__be64 *)(new->virt + (new_idx << 4));
1343 
1344 	replace_vpte = be64_to_cpu(new_hptep[0]);
1345 	if (cpu_has_feature(CPU_FTR_ARCH_300)) {
1346 		unsigned long replace_rpte = be64_to_cpu(new_hptep[1]);
1347 		replace_vpte = hpte_new_to_old_v(replace_vpte, replace_rpte);
1348 	}
1349 
1350 	if (replace_vpte & (HPTE_V_VALID | HPTE_V_ABSENT)) {
1351 		BUG_ON(new->order >= old->order);
1352 
1353 		if (replace_vpte & HPTE_V_BOLTED) {
1354 			if (vpte & HPTE_V_BOLTED)
1355 				/* Bolted collision, nothing we can do */
1356 				ret = -ENOSPC;
1357 			/* Discard the new HPTE */
1358 			goto out;
1359 		}
1360 
1361 		/* Discard the previous HPTE */
1362 	}
1363 
1364 	if (cpu_has_feature(CPU_FTR_ARCH_300)) {
1365 		rpte = hpte_old_to_new_r(vpte, rpte);
1366 		vpte = hpte_old_to_new_v(vpte);
1367 	}
1368 
1369 	new_hptep[1] = cpu_to_be64(rpte);
1370 	new->rev[new_idx].guest_rpte = guest_rpte;
1371 	/* No need for a barrier, since new HPT isn't active */
1372 	new_hptep[0] = cpu_to_be64(vpte);
1373 	unlock_hpte(new_hptep, vpte);
1374 
1375 out:
1376 	unlock_hpte(hptep, vpte);
1377 	preempt_enable();
1378 	return ret;
1379 }
1380 
1381 static int resize_hpt_rehash(struct kvm_resize_hpt *resize)
1382 {
1383 	struct kvm *kvm = resize->kvm;
1384 	unsigned  long i;
1385 	int rc;
1386 
1387 	for (i = 0; i < kvmppc_hpt_npte(&kvm->arch.hpt); i++) {
1388 		rc = resize_hpt_rehash_hpte(resize, i);
1389 		if (rc != 0)
1390 			return rc;
1391 	}
1392 
1393 	return 0;
1394 }
1395 
1396 static void resize_hpt_pivot(struct kvm_resize_hpt *resize)
1397 {
1398 	struct kvm *kvm = resize->kvm;
1399 	struct kvm_hpt_info hpt_tmp;
1400 
1401 	/* Exchange the pending tables in the resize structure with
1402 	 * the active tables */
1403 
1404 	resize_hpt_debug(resize, "resize_hpt_pivot()\n");
1405 
1406 	spin_lock(&kvm->mmu_lock);
1407 	asm volatile("ptesync" : : : "memory");
1408 
1409 	hpt_tmp = kvm->arch.hpt;
1410 	kvmppc_set_hpt(kvm, &resize->hpt);
1411 	resize->hpt = hpt_tmp;
1412 
1413 	spin_unlock(&kvm->mmu_lock);
1414 
1415 	synchronize_srcu_expedited(&kvm->srcu);
1416 
1417 	if (cpu_has_feature(CPU_FTR_ARCH_300))
1418 		kvmppc_setup_partition_table(kvm);
1419 
1420 	resize_hpt_debug(resize, "resize_hpt_pivot() done\n");
1421 }
1422 
1423 static void resize_hpt_release(struct kvm *kvm, struct kvm_resize_hpt *resize)
1424 {
1425 	if (WARN_ON(!mutex_is_locked(&kvm->arch.mmu_setup_lock)))
1426 		return;
1427 
1428 	if (!resize)
1429 		return;
1430 
1431 	if (resize->error != -EBUSY) {
1432 		if (resize->hpt.virt)
1433 			kvmppc_free_hpt(&resize->hpt);
1434 		kfree(resize);
1435 	}
1436 
1437 	if (kvm->arch.resize_hpt == resize)
1438 		kvm->arch.resize_hpt = NULL;
1439 }
1440 
1441 static void resize_hpt_prepare_work(struct work_struct *work)
1442 {
1443 	struct kvm_resize_hpt *resize = container_of(work,
1444 						     struct kvm_resize_hpt,
1445 						     work);
1446 	struct kvm *kvm = resize->kvm;
1447 	int err = 0;
1448 
1449 	if (WARN_ON(resize->error != -EBUSY))
1450 		return;
1451 
1452 	mutex_lock(&kvm->arch.mmu_setup_lock);
1453 
1454 	/* Request is still current? */
1455 	if (kvm->arch.resize_hpt == resize) {
1456 		/* We may request large allocations here:
1457 		 * do not sleep with kvm->arch.mmu_setup_lock held for a while.
1458 		 */
1459 		mutex_unlock(&kvm->arch.mmu_setup_lock);
1460 
1461 		resize_hpt_debug(resize, "%s(): order = %d\n", __func__,
1462 				 resize->order);
1463 
1464 		err = resize_hpt_allocate(resize);
1465 
1466 		/* We have strict assumption about -EBUSY
1467 		 * when preparing for HPT resize.
1468 		 */
1469 		if (WARN_ON(err == -EBUSY))
1470 			err = -EINPROGRESS;
1471 
1472 		mutex_lock(&kvm->arch.mmu_setup_lock);
1473 		/* It is possible that kvm->arch.resize_hpt != resize
1474 		 * after we grab kvm->arch.mmu_setup_lock again.
1475 		 */
1476 	}
1477 
1478 	resize->error = err;
1479 
1480 	if (kvm->arch.resize_hpt != resize)
1481 		resize_hpt_release(kvm, resize);
1482 
1483 	mutex_unlock(&kvm->arch.mmu_setup_lock);
1484 }
1485 
1486 int kvm_vm_ioctl_resize_hpt_prepare(struct kvm *kvm,
1487 				    struct kvm_ppc_resize_hpt *rhpt)
1488 {
1489 	unsigned long flags = rhpt->flags;
1490 	unsigned long shift = rhpt->shift;
1491 	struct kvm_resize_hpt *resize;
1492 	int ret;
1493 
1494 	if (flags != 0 || kvm_is_radix(kvm))
1495 		return -EINVAL;
1496 
1497 	if (shift && ((shift < 18) || (shift > 46)))
1498 		return -EINVAL;
1499 
1500 	mutex_lock(&kvm->arch.mmu_setup_lock);
1501 
1502 	resize = kvm->arch.resize_hpt;
1503 
1504 	if (resize) {
1505 		if (resize->order == shift) {
1506 			/* Suitable resize in progress? */
1507 			ret = resize->error;
1508 			if (ret == -EBUSY)
1509 				ret = 100; /* estimated time in ms */
1510 			else if (ret)
1511 				resize_hpt_release(kvm, resize);
1512 
1513 			goto out;
1514 		}
1515 
1516 		/* not suitable, cancel it */
1517 		resize_hpt_release(kvm, resize);
1518 	}
1519 
1520 	ret = 0;
1521 	if (!shift)
1522 		goto out; /* nothing to do */
1523 
1524 	/* start new resize */
1525 
1526 	resize = kzalloc_obj(*resize);
1527 	if (!resize) {
1528 		ret = -ENOMEM;
1529 		goto out;
1530 	}
1531 
1532 	resize->error = -EBUSY;
1533 	resize->order = shift;
1534 	resize->kvm = kvm;
1535 	INIT_WORK(&resize->work, resize_hpt_prepare_work);
1536 	kvm->arch.resize_hpt = resize;
1537 
1538 	schedule_work(&resize->work);
1539 
1540 	ret = 100; /* estimated time in ms */
1541 
1542 out:
1543 	mutex_unlock(&kvm->arch.mmu_setup_lock);
1544 	return ret;
1545 }
1546 
1547 static void resize_hpt_boot_vcpu(void *opaque)
1548 {
1549 	/* Nothing to do, just force a KVM exit */
1550 }
1551 
1552 int kvm_vm_ioctl_resize_hpt_commit(struct kvm *kvm,
1553 				   struct kvm_ppc_resize_hpt *rhpt)
1554 {
1555 	unsigned long flags = rhpt->flags;
1556 	unsigned long shift = rhpt->shift;
1557 	struct kvm_resize_hpt *resize;
1558 	int ret;
1559 
1560 	if (flags != 0 || kvm_is_radix(kvm))
1561 		return -EINVAL;
1562 
1563 	if (shift && ((shift < 18) || (shift > 46)))
1564 		return -EINVAL;
1565 
1566 	mutex_lock(&kvm->arch.mmu_setup_lock);
1567 
1568 	resize = kvm->arch.resize_hpt;
1569 
1570 	/* This shouldn't be possible */
1571 	ret = -EIO;
1572 	if (WARN_ON(!kvm->arch.mmu_ready))
1573 		goto out_no_hpt;
1574 
1575 	/* Stop VCPUs from running while we mess with the HPT */
1576 	kvm->arch.mmu_ready = 0;
1577 	smp_mb();
1578 
1579 	/* Boot all CPUs out of the guest so they re-read
1580 	 * mmu_ready */
1581 	on_each_cpu(resize_hpt_boot_vcpu, NULL, 1);
1582 
1583 	ret = -ENXIO;
1584 	if (!resize || (resize->order != shift))
1585 		goto out;
1586 
1587 	ret = resize->error;
1588 	if (ret)
1589 		goto out;
1590 
1591 	ret = resize_hpt_rehash(resize);
1592 	if (ret)
1593 		goto out;
1594 
1595 	resize_hpt_pivot(resize);
1596 
1597 out:
1598 	/* Let VCPUs run again */
1599 	kvm->arch.mmu_ready = 1;
1600 	smp_mb();
1601 out_no_hpt:
1602 	resize_hpt_release(kvm, resize);
1603 	mutex_unlock(&kvm->arch.mmu_setup_lock);
1604 	return ret;
1605 }
1606 
1607 /*
1608  * Functions for reading and writing the hash table via reads and
1609  * writes on a file descriptor.
1610  *
1611  * Reads return the guest view of the hash table, which has to be
1612  * pieced together from the real hash table and the guest_rpte
1613  * values in the revmap array.
1614  *
1615  * On writes, each HPTE written is considered in turn, and if it
1616  * is valid, it is written to the HPT as if an H_ENTER with the
1617  * exact flag set was done.  When the invalid count is non-zero
1618  * in the header written to the stream, the kernel will make
1619  * sure that that many HPTEs are invalid, and invalidate them
1620  * if not.
1621  */
1622 
1623 struct kvm_htab_ctx {
1624 	unsigned long	index;
1625 	unsigned long	flags;
1626 	struct kvm	*kvm;
1627 	int		first_pass;
1628 };
1629 
1630 #define HPTE_SIZE	(2 * sizeof(unsigned long))
1631 
1632 /*
1633  * Returns 1 if this HPT entry has been modified or has pending
1634  * R/C bit changes.
1635  */
1636 static int hpte_dirty(struct revmap_entry *revp, __be64 *hptp)
1637 {
1638 	unsigned long rcbits_unset;
1639 
1640 	if (revp->guest_rpte & HPTE_GR_MODIFIED)
1641 		return 1;
1642 
1643 	/* Also need to consider changes in reference and changed bits */
1644 	rcbits_unset = ~revp->guest_rpte & (HPTE_R_R | HPTE_R_C);
1645 	if ((be64_to_cpu(hptp[0]) & HPTE_V_VALID) &&
1646 	    (be64_to_cpu(hptp[1]) & rcbits_unset))
1647 		return 1;
1648 
1649 	return 0;
1650 }
1651 
1652 static long record_hpte(unsigned long flags, __be64 *hptp,
1653 			unsigned long *hpte, struct revmap_entry *revp,
1654 			int want_valid, int first_pass)
1655 {
1656 	unsigned long v, r, hr;
1657 	unsigned long rcbits_unset;
1658 	int ok = 1;
1659 	int valid, dirty;
1660 
1661 	/* Unmodified entries are uninteresting except on the first pass */
1662 	dirty = hpte_dirty(revp, hptp);
1663 	if (!first_pass && !dirty)
1664 		return 0;
1665 
1666 	valid = 0;
1667 	if (be64_to_cpu(hptp[0]) & (HPTE_V_VALID | HPTE_V_ABSENT)) {
1668 		valid = 1;
1669 		if ((flags & KVM_GET_HTAB_BOLTED_ONLY) &&
1670 		    !(be64_to_cpu(hptp[0]) & HPTE_V_BOLTED))
1671 			valid = 0;
1672 	}
1673 	if (valid != want_valid)
1674 		return 0;
1675 
1676 	v = r = 0;
1677 	if (valid || dirty) {
1678 		/* lock the HPTE so it's stable and read it */
1679 		preempt_disable();
1680 		while (!try_lock_hpte(hptp, HPTE_V_HVLOCK))
1681 			cpu_relax();
1682 		v = be64_to_cpu(hptp[0]);
1683 		hr = be64_to_cpu(hptp[1]);
1684 		if (cpu_has_feature(CPU_FTR_ARCH_300)) {
1685 			v = hpte_new_to_old_v(v, hr);
1686 			hr = hpte_new_to_old_r(hr);
1687 		}
1688 
1689 		/* re-evaluate valid and dirty from synchronized HPTE value */
1690 		valid = !!(v & HPTE_V_VALID);
1691 		dirty = !!(revp->guest_rpte & HPTE_GR_MODIFIED);
1692 
1693 		/* Harvest R and C into guest view if necessary */
1694 		rcbits_unset = ~revp->guest_rpte & (HPTE_R_R | HPTE_R_C);
1695 		if (valid && (rcbits_unset & hr)) {
1696 			revp->guest_rpte |= (hr &
1697 				(HPTE_R_R | HPTE_R_C)) | HPTE_GR_MODIFIED;
1698 			dirty = 1;
1699 		}
1700 
1701 		if (v & HPTE_V_ABSENT) {
1702 			v &= ~HPTE_V_ABSENT;
1703 			v |= HPTE_V_VALID;
1704 			valid = 1;
1705 		}
1706 		if ((flags & KVM_GET_HTAB_BOLTED_ONLY) && !(v & HPTE_V_BOLTED))
1707 			valid = 0;
1708 
1709 		r = revp->guest_rpte;
1710 		/* only clear modified if this is the right sort of entry */
1711 		if (valid == want_valid && dirty) {
1712 			r &= ~HPTE_GR_MODIFIED;
1713 			revp->guest_rpte = r;
1714 		}
1715 		unlock_hpte(hptp, be64_to_cpu(hptp[0]));
1716 		preempt_enable();
1717 		if (!(valid == want_valid && (first_pass || dirty)))
1718 			ok = 0;
1719 	}
1720 	hpte[0] = cpu_to_be64(v);
1721 	hpte[1] = cpu_to_be64(r);
1722 	return ok;
1723 }
1724 
1725 static ssize_t kvm_htab_read(struct file *file, char __user *buf,
1726 			     size_t count, loff_t *ppos)
1727 {
1728 	struct kvm_htab_ctx *ctx = file->private_data;
1729 	struct kvm *kvm = ctx->kvm;
1730 	struct kvm_get_htab_header hdr;
1731 	__be64 *hptp;
1732 	struct revmap_entry *revp;
1733 	unsigned long i, nb, nw;
1734 	unsigned long __user *lbuf;
1735 	struct kvm_get_htab_header __user *hptr;
1736 	unsigned long flags;
1737 	int first_pass;
1738 	unsigned long hpte[2];
1739 
1740 	if (!access_ok(buf, count))
1741 		return -EFAULT;
1742 	if (kvm_is_radix(kvm))
1743 		return 0;
1744 
1745 	first_pass = ctx->first_pass;
1746 	flags = ctx->flags;
1747 
1748 	i = ctx->index;
1749 	hptp = (__be64 *)(kvm->arch.hpt.virt + (i * HPTE_SIZE));
1750 	revp = kvm->arch.hpt.rev + i;
1751 	lbuf = (unsigned long __user *)buf;
1752 
1753 	nb = 0;
1754 	while (nb + sizeof(hdr) + HPTE_SIZE < count) {
1755 		/* Initialize header */
1756 		hptr = (struct kvm_get_htab_header __user *)buf;
1757 		hdr.n_valid = 0;
1758 		hdr.n_invalid = 0;
1759 		nw = nb;
1760 		nb += sizeof(hdr);
1761 		lbuf = (unsigned long __user *)(buf + sizeof(hdr));
1762 
1763 		/* Skip uninteresting entries, i.e. clean on not-first pass */
1764 		if (!first_pass) {
1765 			while (i < kvmppc_hpt_npte(&kvm->arch.hpt) &&
1766 			       !hpte_dirty(revp, hptp)) {
1767 				++i;
1768 				hptp += 2;
1769 				++revp;
1770 			}
1771 		}
1772 		hdr.index = i;
1773 
1774 		/* Grab a series of valid entries */
1775 		while (i < kvmppc_hpt_npte(&kvm->arch.hpt) &&
1776 		       hdr.n_valid < 0xffff &&
1777 		       nb + HPTE_SIZE < count &&
1778 		       record_hpte(flags, hptp, hpte, revp, 1, first_pass)) {
1779 			/* valid entry, write it out */
1780 			++hdr.n_valid;
1781 			if (put_user(hpte[0], lbuf) ||
1782 			    put_user(hpte[1], lbuf + 1))
1783 				return -EFAULT;
1784 			nb += HPTE_SIZE;
1785 			lbuf += 2;
1786 			++i;
1787 			hptp += 2;
1788 			++revp;
1789 		}
1790 		/* Now skip invalid entries while we can */
1791 		while (i < kvmppc_hpt_npte(&kvm->arch.hpt) &&
1792 		       hdr.n_invalid < 0xffff &&
1793 		       record_hpte(flags, hptp, hpte, revp, 0, first_pass)) {
1794 			/* found an invalid entry */
1795 			++hdr.n_invalid;
1796 			++i;
1797 			hptp += 2;
1798 			++revp;
1799 		}
1800 
1801 		if (hdr.n_valid || hdr.n_invalid) {
1802 			/* write back the header */
1803 			if (__copy_to_user(hptr, &hdr, sizeof(hdr)))
1804 				return -EFAULT;
1805 			nw = nb;
1806 			buf = (char __user *)lbuf;
1807 		} else {
1808 			nb = nw;
1809 		}
1810 
1811 		/* Check if we've wrapped around the hash table */
1812 		if (i >= kvmppc_hpt_npte(&kvm->arch.hpt)) {
1813 			i = 0;
1814 			ctx->first_pass = 0;
1815 			break;
1816 		}
1817 	}
1818 
1819 	ctx->index = i;
1820 
1821 	return nb;
1822 }
1823 
1824 static ssize_t kvm_htab_write(struct file *file, const char __user *buf,
1825 			      size_t count, loff_t *ppos)
1826 {
1827 	struct kvm_htab_ctx *ctx = file->private_data;
1828 	struct kvm *kvm = ctx->kvm;
1829 	struct kvm_get_htab_header hdr;
1830 	unsigned long i, j;
1831 	unsigned long v, r;
1832 	unsigned long __user *lbuf;
1833 	__be64 *hptp;
1834 	unsigned long tmp[2];
1835 	ssize_t nb;
1836 	long int err, ret;
1837 	int mmu_ready;
1838 	int pshift;
1839 
1840 	if (!access_ok(buf, count))
1841 		return -EFAULT;
1842 	if (kvm_is_radix(kvm))
1843 		return -EINVAL;
1844 
1845 	/* lock out vcpus from running while we're doing this */
1846 	mutex_lock(&kvm->arch.mmu_setup_lock);
1847 	mmu_ready = kvm->arch.mmu_ready;
1848 	if (mmu_ready) {
1849 		kvm->arch.mmu_ready = 0;	/* temporarily */
1850 		/* order mmu_ready vs. vcpus_running */
1851 		smp_mb();
1852 		if (atomic_read(&kvm->arch.vcpus_running)) {
1853 			kvm->arch.mmu_ready = 1;
1854 			mutex_unlock(&kvm->arch.mmu_setup_lock);
1855 			return -EBUSY;
1856 		}
1857 	}
1858 
1859 	err = 0;
1860 	for (nb = 0; nb + sizeof(hdr) <= count; ) {
1861 		err = -EFAULT;
1862 		if (__copy_from_user(&hdr, buf, sizeof(hdr)))
1863 			break;
1864 
1865 		err = 0;
1866 		if (nb + hdr.n_valid * HPTE_SIZE > count)
1867 			break;
1868 
1869 		nb += sizeof(hdr);
1870 		buf += sizeof(hdr);
1871 
1872 		err = -EINVAL;
1873 		i = hdr.index;
1874 		if (i >= kvmppc_hpt_npte(&kvm->arch.hpt) ||
1875 		    i + hdr.n_valid + hdr.n_invalid > kvmppc_hpt_npte(&kvm->arch.hpt))
1876 			break;
1877 
1878 		hptp = (__be64 *)(kvm->arch.hpt.virt + (i * HPTE_SIZE));
1879 		lbuf = (unsigned long __user *)buf;
1880 		for (j = 0; j < hdr.n_valid; ++j) {
1881 			__be64 hpte_v;
1882 			__be64 hpte_r;
1883 
1884 			err = -EFAULT;
1885 			if (get_user(hpte_v, lbuf) ||
1886 			    get_user(hpte_r, lbuf + 1))
1887 				goto out;
1888 			v = be64_to_cpu(hpte_v);
1889 			r = be64_to_cpu(hpte_r);
1890 			err = -EINVAL;
1891 			if (!(v & HPTE_V_VALID))
1892 				goto out;
1893 			pshift = kvmppc_hpte_base_page_shift(v, r);
1894 			if (pshift <= 0)
1895 				goto out;
1896 			lbuf += 2;
1897 			nb += HPTE_SIZE;
1898 
1899 			if (be64_to_cpu(hptp[0]) & (HPTE_V_VALID | HPTE_V_ABSENT))
1900 				kvmppc_virtmode_do_h_remove(kvm, 0, i, 0, tmp);
1901 			err = -EIO;
1902 			ret = kvmppc_virtmode_do_h_enter(kvm, H_EXACT, i, v, r,
1903 							 tmp);
1904 			if (ret != H_SUCCESS) {
1905 				pr_err("%s ret %ld i=%ld v=%lx r=%lx\n", __func__, ret, i, v, r);
1906 				goto out;
1907 			}
1908 			if (!mmu_ready && is_vrma_hpte(v)) {
1909 				unsigned long senc, lpcr;
1910 
1911 				senc = slb_pgsize_encoding(1ul << pshift);
1912 				kvm->arch.vrma_slb_v = senc | SLB_VSID_B_1T |
1913 					(VRMA_VSID << SLB_VSID_SHIFT_1T);
1914 				if (!cpu_has_feature(CPU_FTR_ARCH_300)) {
1915 					lpcr = senc << (LPCR_VRMASD_SH - 4);
1916 					kvmppc_update_lpcr(kvm, lpcr,
1917 							   LPCR_VRMASD);
1918 				} else {
1919 					kvmppc_setup_partition_table(kvm);
1920 				}
1921 				mmu_ready = 1;
1922 			}
1923 			++i;
1924 			hptp += 2;
1925 		}
1926 
1927 		for (j = 0; j < hdr.n_invalid; ++j) {
1928 			if (be64_to_cpu(hptp[0]) & (HPTE_V_VALID | HPTE_V_ABSENT))
1929 				kvmppc_virtmode_do_h_remove(kvm, 0, i, 0, tmp);
1930 			++i;
1931 			hptp += 2;
1932 		}
1933 		err = 0;
1934 	}
1935 
1936  out:
1937 	/* Order HPTE updates vs. mmu_ready */
1938 	smp_wmb();
1939 	kvm->arch.mmu_ready = mmu_ready;
1940 	mutex_unlock(&kvm->arch.mmu_setup_lock);
1941 
1942 	if (err)
1943 		return err;
1944 	return nb;
1945 }
1946 
1947 static int kvm_htab_release(struct inode *inode, struct file *filp)
1948 {
1949 	struct kvm_htab_ctx *ctx = filp->private_data;
1950 
1951 	filp->private_data = NULL;
1952 	if (!(ctx->flags & KVM_GET_HTAB_WRITE))
1953 		atomic_dec(&ctx->kvm->arch.hpte_mod_interest);
1954 	kvm_put_kvm(ctx->kvm);
1955 	kfree(ctx);
1956 	return 0;
1957 }
1958 
1959 static const struct file_operations kvm_htab_fops = {
1960 	.read		= kvm_htab_read,
1961 	.write		= kvm_htab_write,
1962 	.llseek		= default_llseek,
1963 	.release	= kvm_htab_release,
1964 };
1965 
1966 int kvm_vm_ioctl_get_htab_fd(struct kvm *kvm, struct kvm_get_htab_fd *ghf)
1967 {
1968 	int ret;
1969 	struct kvm_htab_ctx *ctx;
1970 	int rwflag;
1971 
1972 	/* reject flags we don't recognize */
1973 	if (ghf->flags & ~(KVM_GET_HTAB_BOLTED_ONLY | KVM_GET_HTAB_WRITE))
1974 		return -EINVAL;
1975 	ctx = kzalloc_obj(*ctx);
1976 	if (!ctx)
1977 		return -ENOMEM;
1978 	kvm_get_kvm(kvm);
1979 	ctx->kvm = kvm;
1980 	ctx->index = ghf->start_index;
1981 	ctx->flags = ghf->flags;
1982 	ctx->first_pass = 1;
1983 
1984 	rwflag = (ghf->flags & KVM_GET_HTAB_WRITE) ? O_WRONLY : O_RDONLY;
1985 	ret = anon_inode_getfd("kvm-htab", &kvm_htab_fops, ctx, rwflag | O_CLOEXEC);
1986 	if (ret < 0) {
1987 		kfree(ctx);
1988 		kvm_put_kvm_no_destroy(kvm);
1989 		return ret;
1990 	}
1991 
1992 	if (rwflag == O_RDONLY) {
1993 		mutex_lock(&kvm->slots_lock);
1994 		atomic_inc(&kvm->arch.hpte_mod_interest);
1995 		/* make sure kvmppc_do_h_enter etc. see the increment */
1996 		synchronize_srcu_expedited(&kvm->srcu);
1997 		mutex_unlock(&kvm->slots_lock);
1998 	}
1999 
2000 	return ret;
2001 }
2002 
2003 struct debugfs_htab_state {
2004 	struct kvm	*kvm;
2005 	struct mutex	mutex;
2006 	unsigned long	hpt_index;
2007 	int		chars_left;
2008 	int		buf_index;
2009 	char		buf[64];
2010 };
2011 
2012 static int debugfs_htab_open(struct inode *inode, struct file *file)
2013 {
2014 	struct kvm *kvm = inode->i_private;
2015 	struct debugfs_htab_state *p;
2016 
2017 	p = kzalloc_obj(*p);
2018 	if (!p)
2019 		return -ENOMEM;
2020 
2021 	kvm_get_kvm(kvm);
2022 	p->kvm = kvm;
2023 	mutex_init(&p->mutex);
2024 	file->private_data = p;
2025 
2026 	return nonseekable_open(inode, file);
2027 }
2028 
2029 static int debugfs_htab_release(struct inode *inode, struct file *file)
2030 {
2031 	struct debugfs_htab_state *p = file->private_data;
2032 
2033 	kvm_put_kvm(p->kvm);
2034 	kfree(p);
2035 	return 0;
2036 }
2037 
2038 static ssize_t debugfs_htab_read(struct file *file, char __user *buf,
2039 				 size_t len, loff_t *ppos)
2040 {
2041 	struct debugfs_htab_state *p = file->private_data;
2042 	ssize_t ret, r;
2043 	unsigned long i, n;
2044 	unsigned long v, hr, gr;
2045 	struct kvm *kvm;
2046 	__be64 *hptp;
2047 
2048 	kvm = p->kvm;
2049 	if (kvm_is_radix(kvm))
2050 		return 0;
2051 
2052 	ret = mutex_lock_interruptible(&p->mutex);
2053 	if (ret)
2054 		return ret;
2055 
2056 	if (p->chars_left) {
2057 		n = p->chars_left;
2058 		if (n > len)
2059 			n = len;
2060 		r = copy_to_user(buf, p->buf + p->buf_index, n);
2061 		n -= r;
2062 		p->chars_left -= n;
2063 		p->buf_index += n;
2064 		buf += n;
2065 		len -= n;
2066 		ret = n;
2067 		if (r) {
2068 			if (!n)
2069 				ret = -EFAULT;
2070 			goto out;
2071 		}
2072 	}
2073 
2074 	i = p->hpt_index;
2075 	hptp = (__be64 *)(kvm->arch.hpt.virt + (i * HPTE_SIZE));
2076 	for (; len != 0 && i < kvmppc_hpt_npte(&kvm->arch.hpt);
2077 	     ++i, hptp += 2) {
2078 		if (!(be64_to_cpu(hptp[0]) & (HPTE_V_VALID | HPTE_V_ABSENT)))
2079 			continue;
2080 
2081 		/* lock the HPTE so it's stable and read it */
2082 		preempt_disable();
2083 		while (!try_lock_hpte(hptp, HPTE_V_HVLOCK))
2084 			cpu_relax();
2085 		v = be64_to_cpu(hptp[0]) & ~HPTE_V_HVLOCK;
2086 		hr = be64_to_cpu(hptp[1]);
2087 		gr = kvm->arch.hpt.rev[i].guest_rpte;
2088 		unlock_hpte(hptp, v);
2089 		preempt_enable();
2090 
2091 		if (!(v & (HPTE_V_VALID | HPTE_V_ABSENT)))
2092 			continue;
2093 
2094 		n = scnprintf(p->buf, sizeof(p->buf),
2095 			      "%6lx %.16lx %.16lx %.16lx\n",
2096 			      i, v, hr, gr);
2097 		p->chars_left = n;
2098 		if (n > len)
2099 			n = len;
2100 		r = copy_to_user(buf, p->buf, n);
2101 		n -= r;
2102 		p->chars_left -= n;
2103 		p->buf_index = n;
2104 		buf += n;
2105 		len -= n;
2106 		ret += n;
2107 		if (r) {
2108 			if (!ret)
2109 				ret = -EFAULT;
2110 			goto out;
2111 		}
2112 	}
2113 	p->hpt_index = i;
2114 
2115  out:
2116 	mutex_unlock(&p->mutex);
2117 	return ret;
2118 }
2119 
2120 static ssize_t debugfs_htab_write(struct file *file, const char __user *buf,
2121 			   size_t len, loff_t *ppos)
2122 {
2123 	return -EACCES;
2124 }
2125 
2126 static const struct file_operations debugfs_htab_fops = {
2127 	.owner	 = THIS_MODULE,
2128 	.open	 = debugfs_htab_open,
2129 	.release = debugfs_htab_release,
2130 	.read	 = debugfs_htab_read,
2131 	.write	 = debugfs_htab_write,
2132 	.llseek	 = generic_file_llseek,
2133 };
2134 
2135 void kvmppc_mmu_debugfs_init(struct kvm *kvm)
2136 {
2137 	debugfs_create_file("htab", 0400, kvm->debugfs_dentry, kvm,
2138 			    &debugfs_htab_fops);
2139 }
2140 
2141 void kvmppc_mmu_book3s_hv_init(struct kvm_vcpu *vcpu)
2142 {
2143 	struct kvmppc_mmu *mmu = &vcpu->arch.mmu;
2144 
2145 	vcpu->arch.slb_nr = 32;		/* POWER7/POWER8 */
2146 
2147 	mmu->xlate = kvmppc_mmu_book3s_64_hv_xlate;
2148 
2149 	vcpu->arch.hflags |= BOOK3S_HFLAG_SLB;
2150 }
2151