1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  *
4  * Copyright 2016 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/anon_inodes.h>
12 #include <linux/file.h>
13 #include <linux/debugfs.h>
14 #include <linux/pgtable.h>
15 
16 #include <asm/kvm_ppc.h>
17 #include <asm/kvm_book3s.h>
18 #include <asm/page.h>
19 #include <asm/mmu.h>
20 #include <asm/pgalloc.h>
21 #include <asm/pte-walk.h>
22 #include <asm/ultravisor.h>
23 #include <asm/kvm_book3s_uvmem.h>
24 #include <asm/plpar_wrappers.h>
25 #include <asm/firmware.h>
26 
27 /*
28  * Supported radix tree geometry.
29  * Like p9, we support either 5 or 9 bits at the first (lowest) level,
30  * for a page size of 64k or 4k.
31  */
32 static int p9_supported_radix_bits[4] = { 5, 9, 9, 13 };
33 
34 unsigned long __kvmhv_copy_tofrom_guest_radix(int lpid, int pid,
35 					      gva_t eaddr, void *to, void *from,
36 					      unsigned long n)
37 {
38 	int old_pid, old_lpid;
39 	unsigned long quadrant, ret = n;
40 	bool is_load = !!to;
41 
42 	/* Can't access quadrants 1 or 2 in non-HV mode, call the HV to do it */
43 	if (kvmhv_on_pseries())
44 		return plpar_hcall_norets(H_COPY_TOFROM_GUEST, lpid, pid, eaddr,
45 					  (to != NULL) ? __pa(to): 0,
46 					  (from != NULL) ? __pa(from): 0, n);
47 
48 	if (eaddr & (0xFFFUL << 52))
49 		return ret;
50 
51 	quadrant = 1;
52 	if (!pid)
53 		quadrant = 2;
54 	if (is_load)
55 		from = (void *) (eaddr | (quadrant << 62));
56 	else
57 		to = (void *) (eaddr | (quadrant << 62));
58 
59 	preempt_disable();
60 
61 	asm volatile("hwsync" ::: "memory");
62 	isync();
63 	/* switch the lpid first to avoid running host with unallocated pid */
64 	old_lpid = mfspr(SPRN_LPID);
65 	if (old_lpid != lpid)
66 		mtspr(SPRN_LPID, lpid);
67 	if (quadrant == 1) {
68 		old_pid = mfspr(SPRN_PID);
69 		if (old_pid != pid)
70 			mtspr(SPRN_PID, pid);
71 	}
72 	isync();
73 
74 	pagefault_disable();
75 	if (is_load)
76 		ret = __copy_from_user_inatomic(to, (const void __user *)from, n);
77 	else
78 		ret = __copy_to_user_inatomic((void __user *)to, from, n);
79 	pagefault_enable();
80 
81 	asm volatile("hwsync" ::: "memory");
82 	isync();
83 	/* switch the pid first to avoid running host with unallocated pid */
84 	if (quadrant == 1 && pid != old_pid)
85 		mtspr(SPRN_PID, old_pid);
86 	if (lpid != old_lpid)
87 		mtspr(SPRN_LPID, old_lpid);
88 	isync();
89 
90 	preempt_enable();
91 
92 	return ret;
93 }
94 
95 static long kvmhv_copy_tofrom_guest_radix(struct kvm_vcpu *vcpu, gva_t eaddr,
96 					  void *to, void *from, unsigned long n)
97 {
98 	int lpid = vcpu->kvm->arch.lpid;
99 	int pid = vcpu->arch.pid;
100 
101 	/* This would cause a data segment intr so don't allow the access */
102 	if (eaddr & (0x3FFUL << 52))
103 		return -EINVAL;
104 
105 	/* Should we be using the nested lpid */
106 	if (vcpu->arch.nested)
107 		lpid = vcpu->arch.nested->shadow_lpid;
108 
109 	/* If accessing quadrant 3 then pid is expected to be 0 */
110 	if (((eaddr >> 62) & 0x3) == 0x3)
111 		pid = 0;
112 
113 	eaddr &= ~(0xFFFUL << 52);
114 
115 	return __kvmhv_copy_tofrom_guest_radix(lpid, pid, eaddr, to, from, n);
116 }
117 
118 long kvmhv_copy_from_guest_radix(struct kvm_vcpu *vcpu, gva_t eaddr, void *to,
119 				 unsigned long n)
120 {
121 	long ret;
122 
123 	ret = kvmhv_copy_tofrom_guest_radix(vcpu, eaddr, to, NULL, n);
124 	if (ret > 0)
125 		memset(to + (n - ret), 0, ret);
126 
127 	return ret;
128 }
129 
130 long kvmhv_copy_to_guest_radix(struct kvm_vcpu *vcpu, gva_t eaddr, void *from,
131 			       unsigned long n)
132 {
133 	return kvmhv_copy_tofrom_guest_radix(vcpu, eaddr, NULL, from, n);
134 }
135 
136 int kvmppc_mmu_walk_radix_tree(struct kvm_vcpu *vcpu, gva_t eaddr,
137 			       struct kvmppc_pte *gpte, u64 root,
138 			       u64 *pte_ret_p)
139 {
140 	struct kvm *kvm = vcpu->kvm;
141 	int ret, level, ps;
142 	unsigned long rts, bits, offset, index;
143 	u64 pte, base, gpa;
144 	__be64 rpte;
145 
146 	rts = ((root & RTS1_MASK) >> (RTS1_SHIFT - 3)) |
147 		((root & RTS2_MASK) >> RTS2_SHIFT);
148 	bits = root & RPDS_MASK;
149 	base = root & RPDB_MASK;
150 
151 	offset = rts + 31;
152 
153 	/* Current implementations only support 52-bit space */
154 	if (offset != 52)
155 		return -EINVAL;
156 
157 	/* Walk each level of the radix tree */
158 	for (level = 3; level >= 0; --level) {
159 		u64 addr;
160 		/* Check a valid size */
161 		if (level && bits != p9_supported_radix_bits[level])
162 			return -EINVAL;
163 		if (level == 0 && !(bits == 5 || bits == 9))
164 			return -EINVAL;
165 		offset -= bits;
166 		index = (eaddr >> offset) & ((1UL << bits) - 1);
167 		/* Check that low bits of page table base are zero */
168 		if (base & ((1UL << (bits + 3)) - 1))
169 			return -EINVAL;
170 		/* Read the entry from guest memory */
171 		addr = base + (index * sizeof(rpte));
172 
173 		kvm_vcpu_srcu_read_lock(vcpu);
174 		ret = kvm_read_guest(kvm, addr, &rpte, sizeof(rpte));
175 		kvm_vcpu_srcu_read_unlock(vcpu);
176 		if (ret) {
177 			if (pte_ret_p)
178 				*pte_ret_p = addr;
179 			return ret;
180 		}
181 		pte = __be64_to_cpu(rpte);
182 		if (!(pte & _PAGE_PRESENT))
183 			return -ENOENT;
184 		/* Check if a leaf entry */
185 		if (pte & _PAGE_PTE)
186 			break;
187 		/* Get ready to walk the next level */
188 		base = pte & RPDB_MASK;
189 		bits = pte & RPDS_MASK;
190 	}
191 
192 	/* Need a leaf at lowest level; 512GB pages not supported */
193 	if (level < 0 || level == 3)
194 		return -EINVAL;
195 
196 	/* We found a valid leaf PTE */
197 	/* Offset is now log base 2 of the page size */
198 	gpa = pte & 0x01fffffffffff000ul;
199 	if (gpa & ((1ul << offset) - 1))
200 		return -EINVAL;
201 	gpa |= eaddr & ((1ul << offset) - 1);
202 	for (ps = MMU_PAGE_4K; ps < MMU_PAGE_COUNT; ++ps)
203 		if (offset == mmu_psize_defs[ps].shift)
204 			break;
205 	gpte->page_size = ps;
206 	gpte->page_shift = offset;
207 
208 	gpte->eaddr = eaddr;
209 	gpte->raddr = gpa;
210 
211 	/* Work out permissions */
212 	gpte->may_read = !!(pte & _PAGE_READ);
213 	gpte->may_write = !!(pte & _PAGE_WRITE);
214 	gpte->may_execute = !!(pte & _PAGE_EXEC);
215 
216 	gpte->rc = pte & (_PAGE_ACCESSED | _PAGE_DIRTY);
217 
218 	if (pte_ret_p)
219 		*pte_ret_p = pte;
220 
221 	return 0;
222 }
223 
224 /*
225  * Used to walk a partition or process table radix tree in guest memory
226  * Note: We exploit the fact that a partition table and a process
227  * table have the same layout, a partition-scoped page table and a
228  * process-scoped page table have the same layout, and the 2nd
229  * doubleword of a partition table entry has the same layout as
230  * the PTCR register.
231  */
232 int kvmppc_mmu_radix_translate_table(struct kvm_vcpu *vcpu, gva_t eaddr,
233 				     struct kvmppc_pte *gpte, u64 table,
234 				     int table_index, u64 *pte_ret_p)
235 {
236 	struct kvm *kvm = vcpu->kvm;
237 	int ret;
238 	unsigned long size, ptbl, root;
239 	struct prtb_entry entry;
240 
241 	if ((table & PRTS_MASK) > 24)
242 		return -EINVAL;
243 	size = 1ul << ((table & PRTS_MASK) + 12);
244 
245 	/* Is the table big enough to contain this entry? */
246 	if ((table_index * sizeof(entry)) >= size)
247 		return -EINVAL;
248 
249 	/* Read the table to find the root of the radix tree */
250 	ptbl = (table & PRTB_MASK) + (table_index * sizeof(entry));
251 	kvm_vcpu_srcu_read_lock(vcpu);
252 	ret = kvm_read_guest(kvm, ptbl, &entry, sizeof(entry));
253 	kvm_vcpu_srcu_read_unlock(vcpu);
254 	if (ret)
255 		return ret;
256 
257 	/* Root is stored in the first double word */
258 	root = be64_to_cpu(entry.prtb0);
259 
260 	return kvmppc_mmu_walk_radix_tree(vcpu, eaddr, gpte, root, pte_ret_p);
261 }
262 
263 int kvmppc_mmu_radix_xlate(struct kvm_vcpu *vcpu, gva_t eaddr,
264 			   struct kvmppc_pte *gpte, bool data, bool iswrite)
265 {
266 	u32 pid;
267 	u64 pte;
268 	int ret;
269 
270 	/* Work out effective PID */
271 	switch (eaddr >> 62) {
272 	case 0:
273 		pid = vcpu->arch.pid;
274 		break;
275 	case 3:
276 		pid = 0;
277 		break;
278 	default:
279 		return -EINVAL;
280 	}
281 
282 	ret = kvmppc_mmu_radix_translate_table(vcpu, eaddr, gpte,
283 				vcpu->kvm->arch.process_table, pid, &pte);
284 	if (ret)
285 		return ret;
286 
287 	/* Check privilege (applies only to process scoped translations) */
288 	if (kvmppc_get_msr(vcpu) & MSR_PR) {
289 		if (pte & _PAGE_PRIVILEGED) {
290 			gpte->may_read = 0;
291 			gpte->may_write = 0;
292 			gpte->may_execute = 0;
293 		}
294 	} else {
295 		if (!(pte & _PAGE_PRIVILEGED)) {
296 			/* Check AMR/IAMR to see if strict mode is in force */
297 			if (vcpu->arch.amr & (1ul << 62))
298 				gpte->may_read = 0;
299 			if (vcpu->arch.amr & (1ul << 63))
300 				gpte->may_write = 0;
301 			if (vcpu->arch.iamr & (1ul << 62))
302 				gpte->may_execute = 0;
303 		}
304 	}
305 
306 	return 0;
307 }
308 
309 void kvmppc_radix_tlbie_page(struct kvm *kvm, unsigned long addr,
310 			     unsigned int pshift, unsigned int lpid)
311 {
312 	unsigned long psize = PAGE_SIZE;
313 	int psi;
314 	long rc;
315 	unsigned long rb;
316 
317 	if (pshift)
318 		psize = 1UL << pshift;
319 	else
320 		pshift = PAGE_SHIFT;
321 
322 	addr &= ~(psize - 1);
323 
324 	if (!kvmhv_on_pseries()) {
325 		radix__flush_tlb_lpid_page(lpid, addr, psize);
326 		return;
327 	}
328 
329 	psi = shift_to_mmu_psize(pshift);
330 
331 	if (!firmware_has_feature(FW_FEATURE_RPT_INVALIDATE)) {
332 		rb = addr | (mmu_get_ap(psi) << PPC_BITLSHIFT(58));
333 		rc = plpar_hcall_norets(H_TLB_INVALIDATE, H_TLBIE_P1_ENC(0, 0, 1),
334 					lpid, rb);
335 	} else {
336 		rc = pseries_rpt_invalidate(lpid, H_RPTI_TARGET_CMMU,
337 					    H_RPTI_TYPE_NESTED |
338 					    H_RPTI_TYPE_TLB,
339 					    psize_to_rpti_pgsize(psi),
340 					    addr, addr + psize);
341 	}
342 
343 	if (rc)
344 		pr_err("KVM: TLB page invalidation hcall failed, rc=%ld\n", rc);
345 }
346 
347 static void kvmppc_radix_flush_pwc(struct kvm *kvm, unsigned int lpid)
348 {
349 	long rc;
350 
351 	if (!kvmhv_on_pseries()) {
352 		radix__flush_pwc_lpid(lpid);
353 		return;
354 	}
355 
356 	if (!firmware_has_feature(FW_FEATURE_RPT_INVALIDATE))
357 		rc = plpar_hcall_norets(H_TLB_INVALIDATE, H_TLBIE_P1_ENC(1, 0, 1),
358 					lpid, TLBIEL_INVAL_SET_LPID);
359 	else
360 		rc = pseries_rpt_invalidate(lpid, H_RPTI_TARGET_CMMU,
361 					    H_RPTI_TYPE_NESTED |
362 					    H_RPTI_TYPE_PWC, H_RPTI_PAGE_ALL,
363 					    0, -1UL);
364 	if (rc)
365 		pr_err("KVM: TLB PWC invalidation hcall failed, rc=%ld\n", rc);
366 }
367 
368 static unsigned long kvmppc_radix_update_pte(struct kvm *kvm, pte_t *ptep,
369 				      unsigned long clr, unsigned long set,
370 				      unsigned long addr, unsigned int shift)
371 {
372 	return __radix_pte_update(ptep, clr, set);
373 }
374 
375 static void kvmppc_radix_set_pte_at(struct kvm *kvm, unsigned long addr,
376 			     pte_t *ptep, pte_t pte)
377 {
378 	radix__set_pte_at(kvm->mm, addr, ptep, pte, 0);
379 }
380 
381 static struct kmem_cache *kvm_pte_cache;
382 static struct kmem_cache *kvm_pmd_cache;
383 
384 static pte_t *kvmppc_pte_alloc(void)
385 {
386 	pte_t *pte;
387 
388 	pte = kmem_cache_alloc(kvm_pte_cache, GFP_KERNEL);
389 	/* pmd_populate() will only reference _pa(pte). */
390 	kmemleak_ignore(pte);
391 
392 	return pte;
393 }
394 
395 static void kvmppc_pte_free(pte_t *ptep)
396 {
397 	kmem_cache_free(kvm_pte_cache, ptep);
398 }
399 
400 static pmd_t *kvmppc_pmd_alloc(void)
401 {
402 	pmd_t *pmd;
403 
404 	pmd = kmem_cache_alloc(kvm_pmd_cache, GFP_KERNEL);
405 	/* pud_populate() will only reference _pa(pmd). */
406 	kmemleak_ignore(pmd);
407 
408 	return pmd;
409 }
410 
411 static void kvmppc_pmd_free(pmd_t *pmdp)
412 {
413 	kmem_cache_free(kvm_pmd_cache, pmdp);
414 }
415 
416 /* Called with kvm->mmu_lock held */
417 void kvmppc_unmap_pte(struct kvm *kvm, pte_t *pte, unsigned long gpa,
418 		      unsigned int shift,
419 		      const struct kvm_memory_slot *memslot,
420 		      unsigned int lpid)
421 
422 {
423 	unsigned long old;
424 	unsigned long gfn = gpa >> PAGE_SHIFT;
425 	unsigned long page_size = PAGE_SIZE;
426 	unsigned long hpa;
427 
428 	old = kvmppc_radix_update_pte(kvm, pte, ~0UL, 0, gpa, shift);
429 	kvmppc_radix_tlbie_page(kvm, gpa, shift, lpid);
430 
431 	/* The following only applies to L1 entries */
432 	if (lpid != kvm->arch.lpid)
433 		return;
434 
435 	if (!memslot) {
436 		memslot = gfn_to_memslot(kvm, gfn);
437 		if (!memslot)
438 			return;
439 	}
440 	if (shift) { /* 1GB or 2MB page */
441 		page_size = 1ul << shift;
442 		if (shift == PMD_SHIFT)
443 			kvm->stat.num_2M_pages--;
444 		else if (shift == PUD_SHIFT)
445 			kvm->stat.num_1G_pages--;
446 	}
447 
448 	gpa &= ~(page_size - 1);
449 	hpa = old & PTE_RPN_MASK;
450 	kvmhv_remove_nest_rmap_range(kvm, memslot, gpa, hpa, page_size);
451 
452 	if ((old & _PAGE_DIRTY) && memslot->dirty_bitmap)
453 		kvmppc_update_dirty_map(memslot, gfn, page_size);
454 }
455 
456 /*
457  * kvmppc_free_p?d are used to free existing page tables, and recursively
458  * descend and clear and free children.
459  * Callers are responsible for flushing the PWC.
460  *
461  * When page tables are being unmapped/freed as part of page fault path
462  * (full == false), valid ptes are generally not expected; however, there
463  * is one situation where they arise, which is when dirty page logging is
464  * turned off for a memslot while the VM is running.  The new memslot
465  * becomes visible to page faults before the memslot commit function
466  * gets to flush the memslot, which can lead to a 2MB page mapping being
467  * installed for a guest physical address where there are already 64kB
468  * (or 4kB) mappings (of sub-pages of the same 2MB page).
469  */
470 static void kvmppc_unmap_free_pte(struct kvm *kvm, pte_t *pte, bool full,
471 				  unsigned int lpid)
472 {
473 	if (full) {
474 		memset(pte, 0, sizeof(long) << RADIX_PTE_INDEX_SIZE);
475 	} else {
476 		pte_t *p = pte;
477 		unsigned long it;
478 
479 		for (it = 0; it < PTRS_PER_PTE; ++it, ++p) {
480 			if (pte_val(*p) == 0)
481 				continue;
482 			kvmppc_unmap_pte(kvm, p,
483 					 pte_pfn(*p) << PAGE_SHIFT,
484 					 PAGE_SHIFT, NULL, lpid);
485 		}
486 	}
487 
488 	kvmppc_pte_free(pte);
489 }
490 
491 static void kvmppc_unmap_free_pmd(struct kvm *kvm, pmd_t *pmd, bool full,
492 				  unsigned int lpid)
493 {
494 	unsigned long im;
495 	pmd_t *p = pmd;
496 
497 	for (im = 0; im < PTRS_PER_PMD; ++im, ++p) {
498 		if (!pmd_present(*p))
499 			continue;
500 		if (pmd_is_leaf(*p)) {
501 			if (full) {
502 				pmd_clear(p);
503 			} else {
504 				WARN_ON_ONCE(1);
505 				kvmppc_unmap_pte(kvm, (pte_t *)p,
506 					 pte_pfn(*(pte_t *)p) << PAGE_SHIFT,
507 					 PMD_SHIFT, NULL, lpid);
508 			}
509 		} else {
510 			pte_t *pte;
511 
512 			pte = pte_offset_map(p, 0);
513 			kvmppc_unmap_free_pte(kvm, pte, full, lpid);
514 			pmd_clear(p);
515 		}
516 	}
517 	kvmppc_pmd_free(pmd);
518 }
519 
520 static void kvmppc_unmap_free_pud(struct kvm *kvm, pud_t *pud,
521 				  unsigned int lpid)
522 {
523 	unsigned long iu;
524 	pud_t *p = pud;
525 
526 	for (iu = 0; iu < PTRS_PER_PUD; ++iu, ++p) {
527 		if (!pud_present(*p))
528 			continue;
529 		if (pud_is_leaf(*p)) {
530 			pud_clear(p);
531 		} else {
532 			pmd_t *pmd;
533 
534 			pmd = pmd_offset(p, 0);
535 			kvmppc_unmap_free_pmd(kvm, pmd, true, lpid);
536 			pud_clear(p);
537 		}
538 	}
539 	pud_free(kvm->mm, pud);
540 }
541 
542 void kvmppc_free_pgtable_radix(struct kvm *kvm, pgd_t *pgd, unsigned int lpid)
543 {
544 	unsigned long ig;
545 
546 	for (ig = 0; ig < PTRS_PER_PGD; ++ig, ++pgd) {
547 		p4d_t *p4d = p4d_offset(pgd, 0);
548 		pud_t *pud;
549 
550 		if (!p4d_present(*p4d))
551 			continue;
552 		pud = pud_offset(p4d, 0);
553 		kvmppc_unmap_free_pud(kvm, pud, lpid);
554 		p4d_clear(p4d);
555 	}
556 }
557 
558 void kvmppc_free_radix(struct kvm *kvm)
559 {
560 	if (kvm->arch.pgtable) {
561 		kvmppc_free_pgtable_radix(kvm, kvm->arch.pgtable,
562 					  kvm->arch.lpid);
563 		pgd_free(kvm->mm, kvm->arch.pgtable);
564 		kvm->arch.pgtable = NULL;
565 	}
566 }
567 
568 static void kvmppc_unmap_free_pmd_entry_table(struct kvm *kvm, pmd_t *pmd,
569 					unsigned long gpa, unsigned int lpid)
570 {
571 	pte_t *pte = pte_offset_kernel(pmd, 0);
572 
573 	/*
574 	 * Clearing the pmd entry then flushing the PWC ensures that the pte
575 	 * page no longer be cached by the MMU, so can be freed without
576 	 * flushing the PWC again.
577 	 */
578 	pmd_clear(pmd);
579 	kvmppc_radix_flush_pwc(kvm, lpid);
580 
581 	kvmppc_unmap_free_pte(kvm, pte, false, lpid);
582 }
583 
584 static void kvmppc_unmap_free_pud_entry_table(struct kvm *kvm, pud_t *pud,
585 					unsigned long gpa, unsigned int lpid)
586 {
587 	pmd_t *pmd = pmd_offset(pud, 0);
588 
589 	/*
590 	 * Clearing the pud entry then flushing the PWC ensures that the pmd
591 	 * page and any children pte pages will no longer be cached by the MMU,
592 	 * so can be freed without flushing the PWC again.
593 	 */
594 	pud_clear(pud);
595 	kvmppc_radix_flush_pwc(kvm, lpid);
596 
597 	kvmppc_unmap_free_pmd(kvm, pmd, false, lpid);
598 }
599 
600 /*
601  * There are a number of bits which may differ between different faults to
602  * the same partition scope entry. RC bits, in the course of cleaning and
603  * aging. And the write bit can change, either the access could have been
604  * upgraded, or a read fault could happen concurrently with a write fault
605  * that sets those bits first.
606  */
607 #define PTE_BITS_MUST_MATCH (~(_PAGE_WRITE | _PAGE_DIRTY | _PAGE_ACCESSED))
608 
609 int kvmppc_create_pte(struct kvm *kvm, pgd_t *pgtable, pte_t pte,
610 		      unsigned long gpa, unsigned int level,
611 		      unsigned long mmu_seq, unsigned int lpid,
612 		      unsigned long *rmapp, struct rmap_nested **n_rmap)
613 {
614 	pgd_t *pgd;
615 	p4d_t *p4d;
616 	pud_t *pud, *new_pud = NULL;
617 	pmd_t *pmd, *new_pmd = NULL;
618 	pte_t *ptep, *new_ptep = NULL;
619 	int ret;
620 
621 	/* Traverse the guest's 2nd-level tree, allocate new levels needed */
622 	pgd = pgtable + pgd_index(gpa);
623 	p4d = p4d_offset(pgd, gpa);
624 
625 	pud = NULL;
626 	if (p4d_present(*p4d))
627 		pud = pud_offset(p4d, gpa);
628 	else
629 		new_pud = pud_alloc_one(kvm->mm, gpa);
630 
631 	pmd = NULL;
632 	if (pud && pud_present(*pud) && !pud_is_leaf(*pud))
633 		pmd = pmd_offset(pud, gpa);
634 	else if (level <= 1)
635 		new_pmd = kvmppc_pmd_alloc();
636 
637 	if (level == 0 && !(pmd && pmd_present(*pmd) && !pmd_is_leaf(*pmd)))
638 		new_ptep = kvmppc_pte_alloc();
639 
640 	/* Check if we might have been invalidated; let the guest retry if so */
641 	spin_lock(&kvm->mmu_lock);
642 	ret = -EAGAIN;
643 	if (mmu_invalidate_retry(kvm, mmu_seq))
644 		goto out_unlock;
645 
646 	/* Now traverse again under the lock and change the tree */
647 	ret = -ENOMEM;
648 	if (p4d_none(*p4d)) {
649 		if (!new_pud)
650 			goto out_unlock;
651 		p4d_populate(kvm->mm, p4d, new_pud);
652 		new_pud = NULL;
653 	}
654 	pud = pud_offset(p4d, gpa);
655 	if (pud_is_leaf(*pud)) {
656 		unsigned long hgpa = gpa & PUD_MASK;
657 
658 		/* Check if we raced and someone else has set the same thing */
659 		if (level == 2) {
660 			if (pud_raw(*pud) == pte_raw(pte)) {
661 				ret = 0;
662 				goto out_unlock;
663 			}
664 			/* Valid 1GB page here already, add our extra bits */
665 			WARN_ON_ONCE((pud_val(*pud) ^ pte_val(pte)) &
666 							PTE_BITS_MUST_MATCH);
667 			kvmppc_radix_update_pte(kvm, (pte_t *)pud,
668 					      0, pte_val(pte), hgpa, PUD_SHIFT);
669 			ret = 0;
670 			goto out_unlock;
671 		}
672 		/*
673 		 * If we raced with another CPU which has just put
674 		 * a 1GB pte in after we saw a pmd page, try again.
675 		 */
676 		if (!new_pmd) {
677 			ret = -EAGAIN;
678 			goto out_unlock;
679 		}
680 		/* Valid 1GB page here already, remove it */
681 		kvmppc_unmap_pte(kvm, (pte_t *)pud, hgpa, PUD_SHIFT, NULL,
682 				 lpid);
683 	}
684 	if (level == 2) {
685 		if (!pud_none(*pud)) {
686 			/*
687 			 * There's a page table page here, but we wanted to
688 			 * install a large page, so remove and free the page
689 			 * table page.
690 			 */
691 			kvmppc_unmap_free_pud_entry_table(kvm, pud, gpa, lpid);
692 		}
693 		kvmppc_radix_set_pte_at(kvm, gpa, (pte_t *)pud, pte);
694 		if (rmapp && n_rmap)
695 			kvmhv_insert_nest_rmap(kvm, rmapp, n_rmap);
696 		ret = 0;
697 		goto out_unlock;
698 	}
699 	if (pud_none(*pud)) {
700 		if (!new_pmd)
701 			goto out_unlock;
702 		pud_populate(kvm->mm, pud, new_pmd);
703 		new_pmd = NULL;
704 	}
705 	pmd = pmd_offset(pud, gpa);
706 	if (pmd_is_leaf(*pmd)) {
707 		unsigned long lgpa = gpa & PMD_MASK;
708 
709 		/* Check if we raced and someone else has set the same thing */
710 		if (level == 1) {
711 			if (pmd_raw(*pmd) == pte_raw(pte)) {
712 				ret = 0;
713 				goto out_unlock;
714 			}
715 			/* Valid 2MB page here already, add our extra bits */
716 			WARN_ON_ONCE((pmd_val(*pmd) ^ pte_val(pte)) &
717 							PTE_BITS_MUST_MATCH);
718 			kvmppc_radix_update_pte(kvm, pmdp_ptep(pmd),
719 					0, pte_val(pte), lgpa, PMD_SHIFT);
720 			ret = 0;
721 			goto out_unlock;
722 		}
723 
724 		/*
725 		 * If we raced with another CPU which has just put
726 		 * a 2MB pte in after we saw a pte page, try again.
727 		 */
728 		if (!new_ptep) {
729 			ret = -EAGAIN;
730 			goto out_unlock;
731 		}
732 		/* Valid 2MB page here already, remove it */
733 		kvmppc_unmap_pte(kvm, pmdp_ptep(pmd), lgpa, PMD_SHIFT, NULL,
734 				 lpid);
735 	}
736 	if (level == 1) {
737 		if (!pmd_none(*pmd)) {
738 			/*
739 			 * There's a page table page here, but we wanted to
740 			 * install a large page, so remove and free the page
741 			 * table page.
742 			 */
743 			kvmppc_unmap_free_pmd_entry_table(kvm, pmd, gpa, lpid);
744 		}
745 		kvmppc_radix_set_pte_at(kvm, gpa, pmdp_ptep(pmd), pte);
746 		if (rmapp && n_rmap)
747 			kvmhv_insert_nest_rmap(kvm, rmapp, n_rmap);
748 		ret = 0;
749 		goto out_unlock;
750 	}
751 	if (pmd_none(*pmd)) {
752 		if (!new_ptep)
753 			goto out_unlock;
754 		pmd_populate(kvm->mm, pmd, new_ptep);
755 		new_ptep = NULL;
756 	}
757 	ptep = pte_offset_kernel(pmd, gpa);
758 	if (pte_present(*ptep)) {
759 		/* Check if someone else set the same thing */
760 		if (pte_raw(*ptep) == pte_raw(pte)) {
761 			ret = 0;
762 			goto out_unlock;
763 		}
764 		/* Valid page here already, add our extra bits */
765 		WARN_ON_ONCE((pte_val(*ptep) ^ pte_val(pte)) &
766 							PTE_BITS_MUST_MATCH);
767 		kvmppc_radix_update_pte(kvm, ptep, 0, pte_val(pte), gpa, 0);
768 		ret = 0;
769 		goto out_unlock;
770 	}
771 	kvmppc_radix_set_pte_at(kvm, gpa, ptep, pte);
772 	if (rmapp && n_rmap)
773 		kvmhv_insert_nest_rmap(kvm, rmapp, n_rmap);
774 	ret = 0;
775 
776  out_unlock:
777 	spin_unlock(&kvm->mmu_lock);
778 	if (new_pud)
779 		pud_free(kvm->mm, new_pud);
780 	if (new_pmd)
781 		kvmppc_pmd_free(new_pmd);
782 	if (new_ptep)
783 		kvmppc_pte_free(new_ptep);
784 	return ret;
785 }
786 
787 bool kvmppc_hv_handle_set_rc(struct kvm *kvm, bool nested, bool writing,
788 			     unsigned long gpa, unsigned int lpid)
789 {
790 	unsigned long pgflags;
791 	unsigned int shift;
792 	pte_t *ptep;
793 
794 	/*
795 	 * Need to set an R or C bit in the 2nd-level tables;
796 	 * since we are just helping out the hardware here,
797 	 * it is sufficient to do what the hardware does.
798 	 */
799 	pgflags = _PAGE_ACCESSED;
800 	if (writing)
801 		pgflags |= _PAGE_DIRTY;
802 
803 	if (nested)
804 		ptep = find_kvm_nested_guest_pte(kvm, lpid, gpa, &shift);
805 	else
806 		ptep = find_kvm_secondary_pte(kvm, gpa, &shift);
807 
808 	if (ptep && pte_present(*ptep) && (!writing || pte_write(*ptep))) {
809 		kvmppc_radix_update_pte(kvm, ptep, 0, pgflags, gpa, shift);
810 		return true;
811 	}
812 	return false;
813 }
814 
815 int kvmppc_book3s_instantiate_page(struct kvm_vcpu *vcpu,
816 				   unsigned long gpa,
817 				   struct kvm_memory_slot *memslot,
818 				   bool writing, bool kvm_ro,
819 				   pte_t *inserted_pte, unsigned int *levelp)
820 {
821 	struct kvm *kvm = vcpu->kvm;
822 	struct page *page = NULL;
823 	unsigned long mmu_seq;
824 	unsigned long hva, gfn = gpa >> PAGE_SHIFT;
825 	bool upgrade_write = false;
826 	bool *upgrade_p = &upgrade_write;
827 	pte_t pte, *ptep;
828 	unsigned int shift, level;
829 	int ret;
830 	bool large_enable;
831 
832 	/* used to check for invalidations in progress */
833 	mmu_seq = kvm->mmu_invalidate_seq;
834 	smp_rmb();
835 
836 	/*
837 	 * Do a fast check first, since __gfn_to_pfn_memslot doesn't
838 	 * do it with !atomic && !async, which is how we call it.
839 	 * We always ask for write permission since the common case
840 	 * is that the page is writable.
841 	 */
842 	hva = gfn_to_hva_memslot(memslot, gfn);
843 	if (!kvm_ro && get_user_page_fast_only(hva, FOLL_WRITE, &page)) {
844 		upgrade_write = true;
845 	} else {
846 		unsigned long pfn;
847 
848 		/* Call KVM generic code to do the slow-path check */
849 		pfn = __gfn_to_pfn_memslot(memslot, gfn, false, false, NULL,
850 					   writing, upgrade_p, NULL);
851 		if (is_error_noslot_pfn(pfn))
852 			return -EFAULT;
853 		page = NULL;
854 		if (pfn_valid(pfn)) {
855 			page = pfn_to_page(pfn);
856 			if (PageReserved(page))
857 				page = NULL;
858 		}
859 	}
860 
861 	/*
862 	 * Read the PTE from the process' radix tree and use that
863 	 * so we get the shift and attribute bits.
864 	 */
865 	spin_lock(&kvm->mmu_lock);
866 	ptep = find_kvm_host_pte(kvm, mmu_seq, hva, &shift);
867 	pte = __pte(0);
868 	if (ptep)
869 		pte = READ_ONCE(*ptep);
870 	spin_unlock(&kvm->mmu_lock);
871 	/*
872 	 * If the PTE disappeared temporarily due to a THP
873 	 * collapse, just return and let the guest try again.
874 	 */
875 	if (!pte_present(pte)) {
876 		if (page)
877 			put_page(page);
878 		return RESUME_GUEST;
879 	}
880 
881 	/* If we're logging dirty pages, always map single pages */
882 	large_enable = !(memslot->flags & KVM_MEM_LOG_DIRTY_PAGES);
883 
884 	/* Get pte level from shift/size */
885 	if (large_enable && shift == PUD_SHIFT &&
886 	    (gpa & (PUD_SIZE - PAGE_SIZE)) ==
887 	    (hva & (PUD_SIZE - PAGE_SIZE))) {
888 		level = 2;
889 	} else if (large_enable && shift == PMD_SHIFT &&
890 		   (gpa & (PMD_SIZE - PAGE_SIZE)) ==
891 		   (hva & (PMD_SIZE - PAGE_SIZE))) {
892 		level = 1;
893 	} else {
894 		level = 0;
895 		if (shift > PAGE_SHIFT) {
896 			/*
897 			 * If the pte maps more than one page, bring over
898 			 * bits from the virtual address to get the real
899 			 * address of the specific single page we want.
900 			 */
901 			unsigned long rpnmask = (1ul << shift) - PAGE_SIZE;
902 			pte = __pte(pte_val(pte) | (hva & rpnmask));
903 		}
904 	}
905 
906 	pte = __pte(pte_val(pte) | _PAGE_EXEC | _PAGE_ACCESSED);
907 	if (writing || upgrade_write) {
908 		if (pte_val(pte) & _PAGE_WRITE)
909 			pte = __pte(pte_val(pte) | _PAGE_DIRTY);
910 	} else {
911 		pte = __pte(pte_val(pte) & ~(_PAGE_WRITE | _PAGE_DIRTY));
912 	}
913 
914 	/* Allocate space in the tree and write the PTE */
915 	ret = kvmppc_create_pte(kvm, kvm->arch.pgtable, pte, gpa, level,
916 				mmu_seq, kvm->arch.lpid, NULL, NULL);
917 	if (inserted_pte)
918 		*inserted_pte = pte;
919 	if (levelp)
920 		*levelp = level;
921 
922 	if (page) {
923 		if (!ret && (pte_val(pte) & _PAGE_WRITE))
924 			set_page_dirty_lock(page);
925 		put_page(page);
926 	}
927 
928 	/* Increment number of large pages if we (successfully) inserted one */
929 	if (!ret) {
930 		if (level == 1)
931 			kvm->stat.num_2M_pages++;
932 		else if (level == 2)
933 			kvm->stat.num_1G_pages++;
934 	}
935 
936 	return ret;
937 }
938 
939 int kvmppc_book3s_radix_page_fault(struct kvm_vcpu *vcpu,
940 				   unsigned long ea, unsigned long dsisr)
941 {
942 	struct kvm *kvm = vcpu->kvm;
943 	unsigned long gpa, gfn;
944 	struct kvm_memory_slot *memslot;
945 	long ret;
946 	bool writing = !!(dsisr & DSISR_ISSTORE);
947 	bool kvm_ro = false;
948 
949 	/* Check for unusual errors */
950 	if (dsisr & DSISR_UNSUPP_MMU) {
951 		pr_err("KVM: Got unsupported MMU fault\n");
952 		return -EFAULT;
953 	}
954 	if (dsisr & DSISR_BADACCESS) {
955 		/* Reflect to the guest as DSI */
956 		pr_err("KVM: Got radix HV page fault with DSISR=%lx\n", dsisr);
957 		kvmppc_core_queue_data_storage(vcpu,
958 				kvmppc_get_msr(vcpu) & SRR1_PREFIXED,
959 				ea, dsisr);
960 		return RESUME_GUEST;
961 	}
962 
963 	/* Translate the logical address */
964 	gpa = vcpu->arch.fault_gpa & ~0xfffUL;
965 	gpa &= ~0xF000000000000000ul;
966 	gfn = gpa >> PAGE_SHIFT;
967 	if (!(dsisr & DSISR_PRTABLE_FAULT))
968 		gpa |= ea & 0xfff;
969 
970 	if (kvm->arch.secure_guest & KVMPPC_SECURE_INIT_DONE)
971 		return kvmppc_send_page_to_uv(kvm, gfn);
972 
973 	/* Get the corresponding memslot */
974 	memslot = gfn_to_memslot(kvm, gfn);
975 
976 	/* No memslot means it's an emulated MMIO region */
977 	if (!memslot || (memslot->flags & KVM_MEMSLOT_INVALID)) {
978 		if (dsisr & (DSISR_PRTABLE_FAULT | DSISR_BADACCESS |
979 			     DSISR_SET_RC)) {
980 			/*
981 			 * Bad address in guest page table tree, or other
982 			 * unusual error - reflect it to the guest as DSI.
983 			 */
984 			kvmppc_core_queue_data_storage(vcpu,
985 					kvmppc_get_msr(vcpu) & SRR1_PREFIXED,
986 					ea, dsisr);
987 			return RESUME_GUEST;
988 		}
989 		return kvmppc_hv_emulate_mmio(vcpu, gpa, ea, writing);
990 	}
991 
992 	if (memslot->flags & KVM_MEM_READONLY) {
993 		if (writing) {
994 			/* give the guest a DSI */
995 			kvmppc_core_queue_data_storage(vcpu,
996 					kvmppc_get_msr(vcpu) & SRR1_PREFIXED,
997 					ea, DSISR_ISSTORE | DSISR_PROTFAULT);
998 			return RESUME_GUEST;
999 		}
1000 		kvm_ro = true;
1001 	}
1002 
1003 	/* Failed to set the reference/change bits */
1004 	if (dsisr & DSISR_SET_RC) {
1005 		spin_lock(&kvm->mmu_lock);
1006 		if (kvmppc_hv_handle_set_rc(kvm, false, writing,
1007 					    gpa, kvm->arch.lpid))
1008 			dsisr &= ~DSISR_SET_RC;
1009 		spin_unlock(&kvm->mmu_lock);
1010 
1011 		if (!(dsisr & (DSISR_BAD_FAULT_64S | DSISR_NOHPTE |
1012 			       DSISR_PROTFAULT | DSISR_SET_RC)))
1013 			return RESUME_GUEST;
1014 	}
1015 
1016 	/* Try to insert a pte */
1017 	ret = kvmppc_book3s_instantiate_page(vcpu, gpa, memslot, writing,
1018 					     kvm_ro, NULL, NULL);
1019 
1020 	if (ret == 0 || ret == -EAGAIN)
1021 		ret = RESUME_GUEST;
1022 	return ret;
1023 }
1024 
1025 /* Called with kvm->mmu_lock held */
1026 void kvm_unmap_radix(struct kvm *kvm, struct kvm_memory_slot *memslot,
1027 		     unsigned long gfn)
1028 {
1029 	pte_t *ptep;
1030 	unsigned long gpa = gfn << PAGE_SHIFT;
1031 	unsigned int shift;
1032 
1033 	if (kvm->arch.secure_guest & KVMPPC_SECURE_INIT_DONE) {
1034 		uv_page_inval(kvm->arch.lpid, gpa, PAGE_SHIFT);
1035 		return;
1036 	}
1037 
1038 	ptep = find_kvm_secondary_pte(kvm, gpa, &shift);
1039 	if (ptep && pte_present(*ptep))
1040 		kvmppc_unmap_pte(kvm, ptep, gpa, shift, memslot,
1041 				 kvm->arch.lpid);
1042 }
1043 
1044 /* Called with kvm->mmu_lock held */
1045 bool kvm_age_radix(struct kvm *kvm, struct kvm_memory_slot *memslot,
1046 		   unsigned long gfn)
1047 {
1048 	pte_t *ptep;
1049 	unsigned long gpa = gfn << PAGE_SHIFT;
1050 	unsigned int shift;
1051 	bool ref = false;
1052 	unsigned long old, *rmapp;
1053 
1054 	if (kvm->arch.secure_guest & KVMPPC_SECURE_INIT_DONE)
1055 		return ref;
1056 
1057 	ptep = find_kvm_secondary_pte(kvm, gpa, &shift);
1058 	if (ptep && pte_present(*ptep) && pte_young(*ptep)) {
1059 		old = kvmppc_radix_update_pte(kvm, ptep, _PAGE_ACCESSED, 0,
1060 					      gpa, shift);
1061 		/* XXX need to flush tlb here? */
1062 		/* Also clear bit in ptes in shadow pgtable for nested guests */
1063 		rmapp = &memslot->arch.rmap[gfn - memslot->base_gfn];
1064 		kvmhv_update_nest_rmap_rc_list(kvm, rmapp, _PAGE_ACCESSED, 0,
1065 					       old & PTE_RPN_MASK,
1066 					       1UL << shift);
1067 		ref = true;
1068 	}
1069 	return ref;
1070 }
1071 
1072 /* Called with kvm->mmu_lock held */
1073 bool kvm_test_age_radix(struct kvm *kvm, struct kvm_memory_slot *memslot,
1074 			unsigned long gfn)
1075 
1076 {
1077 	pte_t *ptep;
1078 	unsigned long gpa = gfn << PAGE_SHIFT;
1079 	unsigned int shift;
1080 	bool ref = false;
1081 
1082 	if (kvm->arch.secure_guest & KVMPPC_SECURE_INIT_DONE)
1083 		return ref;
1084 
1085 	ptep = find_kvm_secondary_pte(kvm, gpa, &shift);
1086 	if (ptep && pte_present(*ptep) && pte_young(*ptep))
1087 		ref = true;
1088 	return ref;
1089 }
1090 
1091 /* Returns the number of PAGE_SIZE pages that are dirty */
1092 static int kvm_radix_test_clear_dirty(struct kvm *kvm,
1093 				struct kvm_memory_slot *memslot, int pagenum)
1094 {
1095 	unsigned long gfn = memslot->base_gfn + pagenum;
1096 	unsigned long gpa = gfn << PAGE_SHIFT;
1097 	pte_t *ptep, pte;
1098 	unsigned int shift;
1099 	int ret = 0;
1100 	unsigned long old, *rmapp;
1101 
1102 	if (kvm->arch.secure_guest & KVMPPC_SECURE_INIT_DONE)
1103 		return ret;
1104 
1105 	/*
1106 	 * For performance reasons we don't hold kvm->mmu_lock while walking the
1107 	 * partition scoped table.
1108 	 */
1109 	ptep = find_kvm_secondary_pte_unlocked(kvm, gpa, &shift);
1110 	if (!ptep)
1111 		return 0;
1112 
1113 	pte = READ_ONCE(*ptep);
1114 	if (pte_present(pte) && pte_dirty(pte)) {
1115 		spin_lock(&kvm->mmu_lock);
1116 		/*
1117 		 * Recheck the pte again
1118 		 */
1119 		if (pte_val(pte) != pte_val(*ptep)) {
1120 			/*
1121 			 * We have KVM_MEM_LOG_DIRTY_PAGES enabled. Hence we can
1122 			 * only find PAGE_SIZE pte entries here. We can continue
1123 			 * to use the pte addr returned by above page table
1124 			 * walk.
1125 			 */
1126 			if (!pte_present(*ptep) || !pte_dirty(*ptep)) {
1127 				spin_unlock(&kvm->mmu_lock);
1128 				return 0;
1129 			}
1130 		}
1131 
1132 		ret = 1;
1133 		VM_BUG_ON(shift);
1134 		old = kvmppc_radix_update_pte(kvm, ptep, _PAGE_DIRTY, 0,
1135 					      gpa, shift);
1136 		kvmppc_radix_tlbie_page(kvm, gpa, shift, kvm->arch.lpid);
1137 		/* Also clear bit in ptes in shadow pgtable for nested guests */
1138 		rmapp = &memslot->arch.rmap[gfn - memslot->base_gfn];
1139 		kvmhv_update_nest_rmap_rc_list(kvm, rmapp, _PAGE_DIRTY, 0,
1140 					       old & PTE_RPN_MASK,
1141 					       1UL << shift);
1142 		spin_unlock(&kvm->mmu_lock);
1143 	}
1144 	return ret;
1145 }
1146 
1147 long kvmppc_hv_get_dirty_log_radix(struct kvm *kvm,
1148 			struct kvm_memory_slot *memslot, unsigned long *map)
1149 {
1150 	unsigned long i, j;
1151 	int npages;
1152 
1153 	for (i = 0; i < memslot->npages; i = j) {
1154 		npages = kvm_radix_test_clear_dirty(kvm, memslot, i);
1155 
1156 		/*
1157 		 * Note that if npages > 0 then i must be a multiple of npages,
1158 		 * since huge pages are only used to back the guest at guest
1159 		 * real addresses that are a multiple of their size.
1160 		 * Since we have at most one PTE covering any given guest
1161 		 * real address, if npages > 1 we can skip to i + npages.
1162 		 */
1163 		j = i + 1;
1164 		if (npages) {
1165 			set_dirty_bits(map, i, npages);
1166 			j = i + npages;
1167 		}
1168 	}
1169 	return 0;
1170 }
1171 
1172 void kvmppc_radix_flush_memslot(struct kvm *kvm,
1173 				const struct kvm_memory_slot *memslot)
1174 {
1175 	unsigned long n;
1176 	pte_t *ptep;
1177 	unsigned long gpa;
1178 	unsigned int shift;
1179 
1180 	if (kvm->arch.secure_guest & KVMPPC_SECURE_INIT_START)
1181 		kvmppc_uvmem_drop_pages(memslot, kvm, true);
1182 
1183 	if (kvm->arch.secure_guest & KVMPPC_SECURE_INIT_DONE)
1184 		return;
1185 
1186 	gpa = memslot->base_gfn << PAGE_SHIFT;
1187 	spin_lock(&kvm->mmu_lock);
1188 	for (n = memslot->npages; n; --n) {
1189 		ptep = find_kvm_secondary_pte(kvm, gpa, &shift);
1190 		if (ptep && pte_present(*ptep))
1191 			kvmppc_unmap_pte(kvm, ptep, gpa, shift, memslot,
1192 					 kvm->arch.lpid);
1193 		gpa += PAGE_SIZE;
1194 	}
1195 	/*
1196 	 * Increase the mmu notifier sequence number to prevent any page
1197 	 * fault that read the memslot earlier from writing a PTE.
1198 	 */
1199 	kvm->mmu_invalidate_seq++;
1200 	spin_unlock(&kvm->mmu_lock);
1201 }
1202 
1203 static void add_rmmu_ap_encoding(struct kvm_ppc_rmmu_info *info,
1204 				 int psize, int *indexp)
1205 {
1206 	if (!mmu_psize_defs[psize].shift)
1207 		return;
1208 	info->ap_encodings[*indexp] = mmu_psize_defs[psize].shift |
1209 		(mmu_psize_defs[psize].ap << 29);
1210 	++(*indexp);
1211 }
1212 
1213 int kvmhv_get_rmmu_info(struct kvm *kvm, struct kvm_ppc_rmmu_info *info)
1214 {
1215 	int i;
1216 
1217 	if (!radix_enabled())
1218 		return -EINVAL;
1219 	memset(info, 0, sizeof(*info));
1220 
1221 	/* 4k page size */
1222 	info->geometries[0].page_shift = 12;
1223 	info->geometries[0].level_bits[0] = 9;
1224 	for (i = 1; i < 4; ++i)
1225 		info->geometries[0].level_bits[i] = p9_supported_radix_bits[i];
1226 	/* 64k page size */
1227 	info->geometries[1].page_shift = 16;
1228 	for (i = 0; i < 4; ++i)
1229 		info->geometries[1].level_bits[i] = p9_supported_radix_bits[i];
1230 
1231 	i = 0;
1232 	add_rmmu_ap_encoding(info, MMU_PAGE_4K, &i);
1233 	add_rmmu_ap_encoding(info, MMU_PAGE_64K, &i);
1234 	add_rmmu_ap_encoding(info, MMU_PAGE_2M, &i);
1235 	add_rmmu_ap_encoding(info, MMU_PAGE_1G, &i);
1236 
1237 	return 0;
1238 }
1239 
1240 int kvmppc_init_vm_radix(struct kvm *kvm)
1241 {
1242 	kvm->arch.pgtable = pgd_alloc(kvm->mm);
1243 	if (!kvm->arch.pgtable)
1244 		return -ENOMEM;
1245 	return 0;
1246 }
1247 
1248 static void pte_ctor(void *addr)
1249 {
1250 	memset(addr, 0, RADIX_PTE_TABLE_SIZE);
1251 }
1252 
1253 static void pmd_ctor(void *addr)
1254 {
1255 	memset(addr, 0, RADIX_PMD_TABLE_SIZE);
1256 }
1257 
1258 struct debugfs_radix_state {
1259 	struct kvm	*kvm;
1260 	struct mutex	mutex;
1261 	unsigned long	gpa;
1262 	int		lpid;
1263 	int		chars_left;
1264 	int		buf_index;
1265 	char		buf[128];
1266 	u8		hdr;
1267 };
1268 
1269 static int debugfs_radix_open(struct inode *inode, struct file *file)
1270 {
1271 	struct kvm *kvm = inode->i_private;
1272 	struct debugfs_radix_state *p;
1273 
1274 	p = kzalloc(sizeof(*p), GFP_KERNEL);
1275 	if (!p)
1276 		return -ENOMEM;
1277 
1278 	kvm_get_kvm(kvm);
1279 	p->kvm = kvm;
1280 	mutex_init(&p->mutex);
1281 	file->private_data = p;
1282 
1283 	return nonseekable_open(inode, file);
1284 }
1285 
1286 static int debugfs_radix_release(struct inode *inode, struct file *file)
1287 {
1288 	struct debugfs_radix_state *p = file->private_data;
1289 
1290 	kvm_put_kvm(p->kvm);
1291 	kfree(p);
1292 	return 0;
1293 }
1294 
1295 static ssize_t debugfs_radix_read(struct file *file, char __user *buf,
1296 				 size_t len, loff_t *ppos)
1297 {
1298 	struct debugfs_radix_state *p = file->private_data;
1299 	ssize_t ret, r;
1300 	unsigned long n;
1301 	struct kvm *kvm;
1302 	unsigned long gpa;
1303 	pgd_t *pgt;
1304 	struct kvm_nested_guest *nested;
1305 	pgd_t *pgdp;
1306 	p4d_t p4d, *p4dp;
1307 	pud_t pud, *pudp;
1308 	pmd_t pmd, *pmdp;
1309 	pte_t *ptep;
1310 	int shift;
1311 	unsigned long pte;
1312 
1313 	kvm = p->kvm;
1314 	if (!kvm_is_radix(kvm))
1315 		return 0;
1316 
1317 	ret = mutex_lock_interruptible(&p->mutex);
1318 	if (ret)
1319 		return ret;
1320 
1321 	if (p->chars_left) {
1322 		n = p->chars_left;
1323 		if (n > len)
1324 			n = len;
1325 		r = copy_to_user(buf, p->buf + p->buf_index, n);
1326 		n -= r;
1327 		p->chars_left -= n;
1328 		p->buf_index += n;
1329 		buf += n;
1330 		len -= n;
1331 		ret = n;
1332 		if (r) {
1333 			if (!n)
1334 				ret = -EFAULT;
1335 			goto out;
1336 		}
1337 	}
1338 
1339 	gpa = p->gpa;
1340 	nested = NULL;
1341 	pgt = NULL;
1342 	while (len != 0 && p->lpid >= 0) {
1343 		if (gpa >= RADIX_PGTABLE_RANGE) {
1344 			gpa = 0;
1345 			pgt = NULL;
1346 			if (nested) {
1347 				kvmhv_put_nested(nested);
1348 				nested = NULL;
1349 			}
1350 			p->lpid = kvmhv_nested_next_lpid(kvm, p->lpid);
1351 			p->hdr = 0;
1352 			if (p->lpid < 0)
1353 				break;
1354 		}
1355 		if (!pgt) {
1356 			if (p->lpid == 0) {
1357 				pgt = kvm->arch.pgtable;
1358 			} else {
1359 				nested = kvmhv_get_nested(kvm, p->lpid, false);
1360 				if (!nested) {
1361 					gpa = RADIX_PGTABLE_RANGE;
1362 					continue;
1363 				}
1364 				pgt = nested->shadow_pgtable;
1365 			}
1366 		}
1367 		n = 0;
1368 		if (!p->hdr) {
1369 			if (p->lpid > 0)
1370 				n = scnprintf(p->buf, sizeof(p->buf),
1371 					      "\nNested LPID %d: ", p->lpid);
1372 			n += scnprintf(p->buf + n, sizeof(p->buf) - n,
1373 				      "pgdir: %lx\n", (unsigned long)pgt);
1374 			p->hdr = 1;
1375 			goto copy;
1376 		}
1377 
1378 		pgdp = pgt + pgd_index(gpa);
1379 		p4dp = p4d_offset(pgdp, gpa);
1380 		p4d = READ_ONCE(*p4dp);
1381 		if (!(p4d_val(p4d) & _PAGE_PRESENT)) {
1382 			gpa = (gpa & P4D_MASK) + P4D_SIZE;
1383 			continue;
1384 		}
1385 
1386 		pudp = pud_offset(&p4d, gpa);
1387 		pud = READ_ONCE(*pudp);
1388 		if (!(pud_val(pud) & _PAGE_PRESENT)) {
1389 			gpa = (gpa & PUD_MASK) + PUD_SIZE;
1390 			continue;
1391 		}
1392 		if (pud_val(pud) & _PAGE_PTE) {
1393 			pte = pud_val(pud);
1394 			shift = PUD_SHIFT;
1395 			goto leaf;
1396 		}
1397 
1398 		pmdp = pmd_offset(&pud, gpa);
1399 		pmd = READ_ONCE(*pmdp);
1400 		if (!(pmd_val(pmd) & _PAGE_PRESENT)) {
1401 			gpa = (gpa & PMD_MASK) + PMD_SIZE;
1402 			continue;
1403 		}
1404 		if (pmd_val(pmd) & _PAGE_PTE) {
1405 			pte = pmd_val(pmd);
1406 			shift = PMD_SHIFT;
1407 			goto leaf;
1408 		}
1409 
1410 		ptep = pte_offset_kernel(&pmd, gpa);
1411 		pte = pte_val(READ_ONCE(*ptep));
1412 		if (!(pte & _PAGE_PRESENT)) {
1413 			gpa += PAGE_SIZE;
1414 			continue;
1415 		}
1416 		shift = PAGE_SHIFT;
1417 	leaf:
1418 		n = scnprintf(p->buf, sizeof(p->buf),
1419 			      " %lx: %lx %d\n", gpa, pte, shift);
1420 		gpa += 1ul << shift;
1421 	copy:
1422 		p->chars_left = n;
1423 		if (n > len)
1424 			n = len;
1425 		r = copy_to_user(buf, p->buf, n);
1426 		n -= r;
1427 		p->chars_left -= n;
1428 		p->buf_index = n;
1429 		buf += n;
1430 		len -= n;
1431 		ret += n;
1432 		if (r) {
1433 			if (!ret)
1434 				ret = -EFAULT;
1435 			break;
1436 		}
1437 	}
1438 	p->gpa = gpa;
1439 	if (nested)
1440 		kvmhv_put_nested(nested);
1441 
1442  out:
1443 	mutex_unlock(&p->mutex);
1444 	return ret;
1445 }
1446 
1447 static ssize_t debugfs_radix_write(struct file *file, const char __user *buf,
1448 			   size_t len, loff_t *ppos)
1449 {
1450 	return -EACCES;
1451 }
1452 
1453 static const struct file_operations debugfs_radix_fops = {
1454 	.owner	 = THIS_MODULE,
1455 	.open	 = debugfs_radix_open,
1456 	.release = debugfs_radix_release,
1457 	.read	 = debugfs_radix_read,
1458 	.write	 = debugfs_radix_write,
1459 	.llseek	 = generic_file_llseek,
1460 };
1461 
1462 void kvmhv_radix_debugfs_init(struct kvm *kvm)
1463 {
1464 	debugfs_create_file("radix", 0400, kvm->debugfs_dentry, kvm,
1465 			    &debugfs_radix_fops);
1466 }
1467 
1468 int kvmppc_radix_init(void)
1469 {
1470 	unsigned long size = sizeof(void *) << RADIX_PTE_INDEX_SIZE;
1471 
1472 	kvm_pte_cache = kmem_cache_create("kvm-pte", size, size, 0, pte_ctor);
1473 	if (!kvm_pte_cache)
1474 		return -ENOMEM;
1475 
1476 	size = sizeof(void *) << RADIX_PMD_INDEX_SIZE;
1477 
1478 	kvm_pmd_cache = kmem_cache_create("kvm-pmd", size, size, 0, pmd_ctor);
1479 	if (!kvm_pmd_cache) {
1480 		kmem_cache_destroy(kvm_pte_cache);
1481 		return -ENOMEM;
1482 	}
1483 
1484 	return 0;
1485 }
1486 
1487 void kvmppc_radix_exit(void)
1488 {
1489 	kmem_cache_destroy(kvm_pte_cache);
1490 	kmem_cache_destroy(kvm_pmd_cache);
1491 }
1492