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