1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright IBM Corporation, 2018
4  * Authors Suraj Jitindar Singh <sjitindarsingh@gmail.com>
5  *	   Paul Mackerras <paulus@ozlabs.org>
6  *
7  * Description: KVM functions specific to running nested KVM-HV guests
8  * on Book3S processors (specifically POWER9 and later).
9  */
10 
11 #include <linux/kernel.h>
12 #include <linux/kvm_host.h>
13 #include <linux/llist.h>
14 #include <linux/pgtable.h>
15 
16 #include <asm/kvm_ppc.h>
17 #include <asm/kvm_book3s.h>
18 #include <asm/mmu.h>
19 #include <asm/pgalloc.h>
20 #include <asm/pte-walk.h>
21 #include <asm/reg.h>
22 #include <asm/plpar_wrappers.h>
23 
24 static struct patb_entry *pseries_partition_tb;
25 
26 static void kvmhv_update_ptbl_cache(struct kvm_nested_guest *gp);
27 static void kvmhv_free_memslot_nest_rmap(struct kvm_memory_slot *free);
28 
29 void kvmhv_save_hv_regs(struct kvm_vcpu *vcpu, struct hv_guest_state *hr)
30 {
31 	struct kvmppc_vcore *vc = vcpu->arch.vcore;
32 
33 	hr->pcr = vc->pcr | PCR_MASK;
34 	hr->dpdes = vc->dpdes;
35 	hr->hfscr = vcpu->arch.hfscr;
36 	hr->tb_offset = vc->tb_offset;
37 	hr->dawr0 = vcpu->arch.dawr0;
38 	hr->dawrx0 = vcpu->arch.dawrx0;
39 	hr->ciabr = vcpu->arch.ciabr;
40 	hr->purr = vcpu->arch.purr;
41 	hr->spurr = vcpu->arch.spurr;
42 	hr->ic = vcpu->arch.ic;
43 	hr->vtb = vc->vtb;
44 	hr->srr0 = vcpu->arch.shregs.srr0;
45 	hr->srr1 = vcpu->arch.shregs.srr1;
46 	hr->sprg[0] = vcpu->arch.shregs.sprg0;
47 	hr->sprg[1] = vcpu->arch.shregs.sprg1;
48 	hr->sprg[2] = vcpu->arch.shregs.sprg2;
49 	hr->sprg[3] = vcpu->arch.shregs.sprg3;
50 	hr->pidr = vcpu->arch.pid;
51 	hr->cfar = vcpu->arch.cfar;
52 	hr->ppr = vcpu->arch.ppr;
53 	hr->dawr1 = vcpu->arch.dawr1;
54 	hr->dawrx1 = vcpu->arch.dawrx1;
55 }
56 
57 /* Use noinline_for_stack due to https://bugs.llvm.org/show_bug.cgi?id=49610 */
58 static noinline_for_stack void byteswap_pt_regs(struct pt_regs *regs)
59 {
60 	unsigned long *addr = (unsigned long *) regs;
61 
62 	for (; addr < ((unsigned long *) (regs + 1)); addr++)
63 		*addr = swab64(*addr);
64 }
65 
66 static void byteswap_hv_regs(struct hv_guest_state *hr)
67 {
68 	hr->version = swab64(hr->version);
69 	hr->lpid = swab32(hr->lpid);
70 	hr->vcpu_token = swab32(hr->vcpu_token);
71 	hr->lpcr = swab64(hr->lpcr);
72 	hr->pcr = swab64(hr->pcr) | PCR_MASK;
73 	hr->amor = swab64(hr->amor);
74 	hr->dpdes = swab64(hr->dpdes);
75 	hr->hfscr = swab64(hr->hfscr);
76 	hr->tb_offset = swab64(hr->tb_offset);
77 	hr->dawr0 = swab64(hr->dawr0);
78 	hr->dawrx0 = swab64(hr->dawrx0);
79 	hr->ciabr = swab64(hr->ciabr);
80 	hr->hdec_expiry = swab64(hr->hdec_expiry);
81 	hr->purr = swab64(hr->purr);
82 	hr->spurr = swab64(hr->spurr);
83 	hr->ic = swab64(hr->ic);
84 	hr->vtb = swab64(hr->vtb);
85 	hr->hdar = swab64(hr->hdar);
86 	hr->hdsisr = swab64(hr->hdsisr);
87 	hr->heir = swab64(hr->heir);
88 	hr->asdr = swab64(hr->asdr);
89 	hr->srr0 = swab64(hr->srr0);
90 	hr->srr1 = swab64(hr->srr1);
91 	hr->sprg[0] = swab64(hr->sprg[0]);
92 	hr->sprg[1] = swab64(hr->sprg[1]);
93 	hr->sprg[2] = swab64(hr->sprg[2]);
94 	hr->sprg[3] = swab64(hr->sprg[3]);
95 	hr->pidr = swab64(hr->pidr);
96 	hr->cfar = swab64(hr->cfar);
97 	hr->ppr = swab64(hr->ppr);
98 	hr->dawr1 = swab64(hr->dawr1);
99 	hr->dawrx1 = swab64(hr->dawrx1);
100 }
101 
102 static void save_hv_return_state(struct kvm_vcpu *vcpu, int trap,
103 				 struct hv_guest_state *hr)
104 {
105 	struct kvmppc_vcore *vc = vcpu->arch.vcore;
106 
107 	hr->dpdes = vc->dpdes;
108 	hr->hfscr = vcpu->arch.hfscr;
109 	hr->purr = vcpu->arch.purr;
110 	hr->spurr = vcpu->arch.spurr;
111 	hr->ic = vcpu->arch.ic;
112 	hr->vtb = vc->vtb;
113 	hr->srr0 = vcpu->arch.shregs.srr0;
114 	hr->srr1 = vcpu->arch.shregs.srr1;
115 	hr->sprg[0] = vcpu->arch.shregs.sprg0;
116 	hr->sprg[1] = vcpu->arch.shregs.sprg1;
117 	hr->sprg[2] = vcpu->arch.shregs.sprg2;
118 	hr->sprg[3] = vcpu->arch.shregs.sprg3;
119 	hr->pidr = vcpu->arch.pid;
120 	hr->cfar = vcpu->arch.cfar;
121 	hr->ppr = vcpu->arch.ppr;
122 	switch (trap) {
123 	case BOOK3S_INTERRUPT_H_DATA_STORAGE:
124 		hr->hdar = vcpu->arch.fault_dar;
125 		hr->hdsisr = vcpu->arch.fault_dsisr;
126 		hr->asdr = vcpu->arch.fault_gpa;
127 		break;
128 	case BOOK3S_INTERRUPT_H_INST_STORAGE:
129 		hr->asdr = vcpu->arch.fault_gpa;
130 		break;
131 	case BOOK3S_INTERRUPT_H_EMUL_ASSIST:
132 		hr->heir = vcpu->arch.emul_inst;
133 		break;
134 	}
135 }
136 
137 /*
138  * This can result in some L0 HV register state being leaked to an L1
139  * hypervisor when the hv_guest_state is copied back to the guest after
140  * being modified here.
141  *
142  * There is no known problem with such a leak, and in many cases these
143  * register settings could be derived by the guest by observing behaviour
144  * and timing, interrupts, etc., but it is an issue to consider.
145  */
146 static void sanitise_hv_regs(struct kvm_vcpu *vcpu, struct hv_guest_state *hr)
147 {
148 	struct kvmppc_vcore *vc = vcpu->arch.vcore;
149 	u64 mask;
150 
151 	/*
152 	 * Don't let L1 change LPCR bits for the L2 except these:
153 	 */
154 	mask = LPCR_DPFD | LPCR_ILE | LPCR_TC | LPCR_AIL | LPCR_LD |
155 		LPCR_LPES | LPCR_MER;
156 
157 	/*
158 	 * Additional filtering is required depending on hardware
159 	 * and configuration.
160 	 */
161 	hr->lpcr = kvmppc_filter_lpcr_hv(vcpu->kvm,
162 			(vc->lpcr & ~mask) | (hr->lpcr & mask));
163 
164 	/*
165 	 * Don't let L1 enable features for L2 which we've disabled for L1,
166 	 * but preserve the interrupt cause field.
167 	 */
168 	hr->hfscr &= (HFSCR_INTR_CAUSE | vcpu->arch.hfscr);
169 
170 	/* Don't let data address watchpoint match in hypervisor state */
171 	hr->dawrx0 &= ~DAWRX_HYP;
172 	hr->dawrx1 &= ~DAWRX_HYP;
173 
174 	/* Don't let completed instruction address breakpt match in HV state */
175 	if ((hr->ciabr & CIABR_PRIV) == CIABR_PRIV_HYPER)
176 		hr->ciabr &= ~CIABR_PRIV;
177 }
178 
179 static void restore_hv_regs(struct kvm_vcpu *vcpu, struct hv_guest_state *hr)
180 {
181 	struct kvmppc_vcore *vc = vcpu->arch.vcore;
182 
183 	vc->pcr = hr->pcr | PCR_MASK;
184 	vc->dpdes = hr->dpdes;
185 	vcpu->arch.hfscr = hr->hfscr;
186 	vcpu->arch.dawr0 = hr->dawr0;
187 	vcpu->arch.dawrx0 = hr->dawrx0;
188 	vcpu->arch.ciabr = hr->ciabr;
189 	vcpu->arch.purr = hr->purr;
190 	vcpu->arch.spurr = hr->spurr;
191 	vcpu->arch.ic = hr->ic;
192 	vc->vtb = hr->vtb;
193 	vcpu->arch.shregs.srr0 = hr->srr0;
194 	vcpu->arch.shregs.srr1 = hr->srr1;
195 	vcpu->arch.shregs.sprg0 = hr->sprg[0];
196 	vcpu->arch.shregs.sprg1 = hr->sprg[1];
197 	vcpu->arch.shregs.sprg2 = hr->sprg[2];
198 	vcpu->arch.shregs.sprg3 = hr->sprg[3];
199 	vcpu->arch.pid = hr->pidr;
200 	vcpu->arch.cfar = hr->cfar;
201 	vcpu->arch.ppr = hr->ppr;
202 	vcpu->arch.dawr1 = hr->dawr1;
203 	vcpu->arch.dawrx1 = hr->dawrx1;
204 }
205 
206 void kvmhv_restore_hv_return_state(struct kvm_vcpu *vcpu,
207 				   struct hv_guest_state *hr)
208 {
209 	struct kvmppc_vcore *vc = vcpu->arch.vcore;
210 
211 	vc->dpdes = hr->dpdes;
212 	vcpu->arch.hfscr = hr->hfscr;
213 	vcpu->arch.purr = hr->purr;
214 	vcpu->arch.spurr = hr->spurr;
215 	vcpu->arch.ic = hr->ic;
216 	vc->vtb = hr->vtb;
217 	vcpu->arch.fault_dar = hr->hdar;
218 	vcpu->arch.fault_dsisr = hr->hdsisr;
219 	vcpu->arch.fault_gpa = hr->asdr;
220 	vcpu->arch.emul_inst = hr->heir;
221 	vcpu->arch.shregs.srr0 = hr->srr0;
222 	vcpu->arch.shregs.srr1 = hr->srr1;
223 	vcpu->arch.shregs.sprg0 = hr->sprg[0];
224 	vcpu->arch.shregs.sprg1 = hr->sprg[1];
225 	vcpu->arch.shregs.sprg2 = hr->sprg[2];
226 	vcpu->arch.shregs.sprg3 = hr->sprg[3];
227 	vcpu->arch.pid = hr->pidr;
228 	vcpu->arch.cfar = hr->cfar;
229 	vcpu->arch.ppr = hr->ppr;
230 }
231 
232 static void kvmhv_nested_mmio_needed(struct kvm_vcpu *vcpu, u64 regs_ptr)
233 {
234 	/* No need to reflect the page fault to L1, we've handled it */
235 	vcpu->arch.trap = 0;
236 
237 	/*
238 	 * Since the L2 gprs have already been written back into L1 memory when
239 	 * we complete the mmio, store the L1 memory location of the L2 gpr
240 	 * being loaded into by the mmio so that the loaded value can be
241 	 * written there in kvmppc_complete_mmio_load()
242 	 */
243 	if (((vcpu->arch.io_gpr & KVM_MMIO_REG_EXT_MASK) == KVM_MMIO_REG_GPR)
244 	    && (vcpu->mmio_is_write == 0)) {
245 		vcpu->arch.nested_io_gpr = (gpa_t) regs_ptr +
246 					   offsetof(struct pt_regs,
247 						    gpr[vcpu->arch.io_gpr]);
248 		vcpu->arch.io_gpr = KVM_MMIO_REG_NESTED_GPR;
249 	}
250 }
251 
252 static int kvmhv_read_guest_state_and_regs(struct kvm_vcpu *vcpu,
253 					   struct hv_guest_state *l2_hv,
254 					   struct pt_regs *l2_regs,
255 					   u64 hv_ptr, u64 regs_ptr)
256 {
257 	int size;
258 
259 	if (kvm_vcpu_read_guest(vcpu, hv_ptr, &l2_hv->version,
260 				sizeof(l2_hv->version)))
261 		return -1;
262 
263 	if (kvmppc_need_byteswap(vcpu))
264 		l2_hv->version = swab64(l2_hv->version);
265 
266 	size = hv_guest_state_size(l2_hv->version);
267 	if (size < 0)
268 		return -1;
269 
270 	return kvm_vcpu_read_guest(vcpu, hv_ptr, l2_hv, size) ||
271 		kvm_vcpu_read_guest(vcpu, regs_ptr, l2_regs,
272 				    sizeof(struct pt_regs));
273 }
274 
275 static int kvmhv_write_guest_state_and_regs(struct kvm_vcpu *vcpu,
276 					    struct hv_guest_state *l2_hv,
277 					    struct pt_regs *l2_regs,
278 					    u64 hv_ptr, u64 regs_ptr)
279 {
280 	int size;
281 
282 	size = hv_guest_state_size(l2_hv->version);
283 	if (size < 0)
284 		return -1;
285 
286 	return kvm_vcpu_write_guest(vcpu, hv_ptr, l2_hv, size) ||
287 		kvm_vcpu_write_guest(vcpu, regs_ptr, l2_regs,
288 				     sizeof(struct pt_regs));
289 }
290 
291 long kvmhv_enter_nested_guest(struct kvm_vcpu *vcpu)
292 {
293 	long int err, r;
294 	struct kvm_nested_guest *l2;
295 	struct pt_regs l2_regs, saved_l1_regs;
296 	struct hv_guest_state l2_hv = {0}, saved_l1_hv;
297 	struct kvmppc_vcore *vc = vcpu->arch.vcore;
298 	u64 hv_ptr, regs_ptr;
299 	u64 hdec_exp;
300 	s64 delta_purr, delta_spurr, delta_ic, delta_vtb;
301 
302 	if (vcpu->kvm->arch.l1_ptcr == 0)
303 		return H_NOT_AVAILABLE;
304 
305 	/* copy parameters in */
306 	hv_ptr = kvmppc_get_gpr(vcpu, 4);
307 	regs_ptr = kvmppc_get_gpr(vcpu, 5);
308 	vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
309 	err = kvmhv_read_guest_state_and_regs(vcpu, &l2_hv, &l2_regs,
310 					      hv_ptr, regs_ptr);
311 	srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
312 	if (err)
313 		return H_PARAMETER;
314 
315 	if (kvmppc_need_byteswap(vcpu))
316 		byteswap_hv_regs(&l2_hv);
317 	if (l2_hv.version > HV_GUEST_STATE_VERSION)
318 		return H_P2;
319 
320 	if (kvmppc_need_byteswap(vcpu))
321 		byteswap_pt_regs(&l2_regs);
322 	if (l2_hv.vcpu_token >= NR_CPUS)
323 		return H_PARAMETER;
324 
325 	/* translate lpid */
326 	l2 = kvmhv_get_nested(vcpu->kvm, l2_hv.lpid, true);
327 	if (!l2)
328 		return H_PARAMETER;
329 	if (!l2->l1_gr_to_hr) {
330 		mutex_lock(&l2->tlb_lock);
331 		kvmhv_update_ptbl_cache(l2);
332 		mutex_unlock(&l2->tlb_lock);
333 	}
334 
335 	/* save l1 values of things */
336 	vcpu->arch.regs.msr = vcpu->arch.shregs.msr;
337 	saved_l1_regs = vcpu->arch.regs;
338 	kvmhv_save_hv_regs(vcpu, &saved_l1_hv);
339 
340 	/* convert TB values/offsets to host (L0) values */
341 	hdec_exp = l2_hv.hdec_expiry - vc->tb_offset;
342 	vc->tb_offset += l2_hv.tb_offset;
343 
344 	/* set L1 state to L2 state */
345 	vcpu->arch.nested = l2;
346 	vcpu->arch.nested_vcpu_id = l2_hv.vcpu_token;
347 	vcpu->arch.regs = l2_regs;
348 
349 	/* Guest must always run with ME enabled, HV disabled. */
350 	vcpu->arch.shregs.msr = (vcpu->arch.regs.msr | MSR_ME) & ~MSR_HV;
351 
352 	sanitise_hv_regs(vcpu, &l2_hv);
353 	restore_hv_regs(vcpu, &l2_hv);
354 
355 	vcpu->arch.ret = RESUME_GUEST;
356 	vcpu->arch.trap = 0;
357 	do {
358 		if (mftb() >= hdec_exp) {
359 			vcpu->arch.trap = BOOK3S_INTERRUPT_HV_DECREMENTER;
360 			r = RESUME_HOST;
361 			break;
362 		}
363 		r = kvmhv_run_single_vcpu(vcpu, hdec_exp, l2_hv.lpcr);
364 	} while (is_kvmppc_resume_guest(r));
365 
366 	/* save L2 state for return */
367 	l2_regs = vcpu->arch.regs;
368 	l2_regs.msr = vcpu->arch.shregs.msr;
369 	delta_purr = vcpu->arch.purr - l2_hv.purr;
370 	delta_spurr = vcpu->arch.spurr - l2_hv.spurr;
371 	delta_ic = vcpu->arch.ic - l2_hv.ic;
372 	delta_vtb = vc->vtb - l2_hv.vtb;
373 	save_hv_return_state(vcpu, vcpu->arch.trap, &l2_hv);
374 
375 	/* restore L1 state */
376 	vcpu->arch.nested = NULL;
377 	vcpu->arch.regs = saved_l1_regs;
378 	vcpu->arch.shregs.msr = saved_l1_regs.msr & ~MSR_TS_MASK;
379 	/* set L1 MSR TS field according to L2 transaction state */
380 	if (l2_regs.msr & MSR_TS_MASK)
381 		vcpu->arch.shregs.msr |= MSR_TS_S;
382 	vc->tb_offset = saved_l1_hv.tb_offset;
383 	restore_hv_regs(vcpu, &saved_l1_hv);
384 	vcpu->arch.purr += delta_purr;
385 	vcpu->arch.spurr += delta_spurr;
386 	vcpu->arch.ic += delta_ic;
387 	vc->vtb += delta_vtb;
388 
389 	kvmhv_put_nested(l2);
390 
391 	/* copy l2_hv_state and regs back to guest */
392 	if (kvmppc_need_byteswap(vcpu)) {
393 		byteswap_hv_regs(&l2_hv);
394 		byteswap_pt_regs(&l2_regs);
395 	}
396 	vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
397 	err = kvmhv_write_guest_state_and_regs(vcpu, &l2_hv, &l2_regs,
398 					       hv_ptr, regs_ptr);
399 	srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
400 	if (err)
401 		return H_AUTHORITY;
402 
403 	if (r == -EINTR)
404 		return H_INTERRUPT;
405 
406 	if (vcpu->mmio_needed) {
407 		kvmhv_nested_mmio_needed(vcpu, regs_ptr);
408 		return H_TOO_HARD;
409 	}
410 
411 	return vcpu->arch.trap;
412 }
413 
414 long kvmhv_nested_init(void)
415 {
416 	long int ptb_order;
417 	unsigned long ptcr;
418 	long rc;
419 
420 	if (!kvmhv_on_pseries())
421 		return 0;
422 	if (!radix_enabled())
423 		return -ENODEV;
424 
425 	/* find log base 2 of KVMPPC_NR_LPIDS, rounding up */
426 	ptb_order = __ilog2(KVMPPC_NR_LPIDS - 1) + 1;
427 	if (ptb_order < 8)
428 		ptb_order = 8;
429 	pseries_partition_tb = kmalloc(sizeof(struct patb_entry) << ptb_order,
430 				       GFP_KERNEL);
431 	if (!pseries_partition_tb) {
432 		pr_err("kvm-hv: failed to allocated nested partition table\n");
433 		return -ENOMEM;
434 	}
435 
436 	ptcr = __pa(pseries_partition_tb) | (ptb_order - 8);
437 	rc = plpar_hcall_norets(H_SET_PARTITION_TABLE, ptcr);
438 	if (rc != H_SUCCESS) {
439 		pr_err("kvm-hv: Parent hypervisor does not support nesting (rc=%ld)\n",
440 		       rc);
441 		kfree(pseries_partition_tb);
442 		pseries_partition_tb = NULL;
443 		return -ENODEV;
444 	}
445 
446 	return 0;
447 }
448 
449 void kvmhv_nested_exit(void)
450 {
451 	/*
452 	 * N.B. the kvmhv_on_pseries() test is there because it enables
453 	 * the compiler to remove the call to plpar_hcall_norets()
454 	 * when CONFIG_PPC_PSERIES=n.
455 	 */
456 	if (kvmhv_on_pseries() && pseries_partition_tb) {
457 		plpar_hcall_norets(H_SET_PARTITION_TABLE, 0);
458 		kfree(pseries_partition_tb);
459 		pseries_partition_tb = NULL;
460 	}
461 }
462 
463 static void kvmhv_flush_lpid(unsigned int lpid)
464 {
465 	long rc;
466 
467 	if (!kvmhv_on_pseries()) {
468 		radix__flush_all_lpid(lpid);
469 		return;
470 	}
471 
472 	if (!firmware_has_feature(FW_FEATURE_RPT_INVALIDATE))
473 		rc = plpar_hcall_norets(H_TLB_INVALIDATE, H_TLBIE_P1_ENC(2, 0, 1),
474 					lpid, TLBIEL_INVAL_SET_LPID);
475 	else
476 		rc = pseries_rpt_invalidate(lpid, H_RPTI_TARGET_CMMU,
477 					    H_RPTI_TYPE_NESTED |
478 					    H_RPTI_TYPE_TLB | H_RPTI_TYPE_PWC |
479 					    H_RPTI_TYPE_PAT,
480 					    H_RPTI_PAGE_ALL, 0, -1UL);
481 	if (rc)
482 		pr_err("KVM: TLB LPID invalidation hcall failed, rc=%ld\n", rc);
483 }
484 
485 void kvmhv_set_ptbl_entry(unsigned int lpid, u64 dw0, u64 dw1)
486 {
487 	if (!kvmhv_on_pseries()) {
488 		mmu_partition_table_set_entry(lpid, dw0, dw1, true);
489 		return;
490 	}
491 
492 	pseries_partition_tb[lpid].patb0 = cpu_to_be64(dw0);
493 	pseries_partition_tb[lpid].patb1 = cpu_to_be64(dw1);
494 	/* L0 will do the necessary barriers */
495 	kvmhv_flush_lpid(lpid);
496 }
497 
498 static void kvmhv_set_nested_ptbl(struct kvm_nested_guest *gp)
499 {
500 	unsigned long dw0;
501 
502 	dw0 = PATB_HR | radix__get_tree_size() |
503 		__pa(gp->shadow_pgtable) | RADIX_PGD_INDEX_SIZE;
504 	kvmhv_set_ptbl_entry(gp->shadow_lpid, dw0, gp->process_table);
505 }
506 
507 void kvmhv_vm_nested_init(struct kvm *kvm)
508 {
509 	kvm->arch.max_nested_lpid = -1;
510 }
511 
512 /*
513  * Handle the H_SET_PARTITION_TABLE hcall.
514  * r4 = guest real address of partition table + log_2(size) - 12
515  * (formatted as for the PTCR).
516  */
517 long kvmhv_set_partition_table(struct kvm_vcpu *vcpu)
518 {
519 	struct kvm *kvm = vcpu->kvm;
520 	unsigned long ptcr = kvmppc_get_gpr(vcpu, 4);
521 	int srcu_idx;
522 	long ret = H_SUCCESS;
523 
524 	srcu_idx = srcu_read_lock(&kvm->srcu);
525 	/*
526 	 * Limit the partition table to 4096 entries (because that's what
527 	 * hardware supports), and check the base address.
528 	 */
529 	if ((ptcr & PRTS_MASK) > 12 - 8 ||
530 	    !kvm_is_visible_gfn(vcpu->kvm, (ptcr & PRTB_MASK) >> PAGE_SHIFT))
531 		ret = H_PARAMETER;
532 	srcu_read_unlock(&kvm->srcu, srcu_idx);
533 	if (ret == H_SUCCESS)
534 		kvm->arch.l1_ptcr = ptcr;
535 	return ret;
536 }
537 
538 /*
539  * Handle the H_COPY_TOFROM_GUEST hcall.
540  * r4 = L1 lpid of nested guest
541  * r5 = pid
542  * r6 = eaddr to access
543  * r7 = to buffer (L1 gpa)
544  * r8 = from buffer (L1 gpa)
545  * r9 = n bytes to copy
546  */
547 long kvmhv_copy_tofrom_guest_nested(struct kvm_vcpu *vcpu)
548 {
549 	struct kvm_nested_guest *gp;
550 	int l1_lpid = kvmppc_get_gpr(vcpu, 4);
551 	int pid = kvmppc_get_gpr(vcpu, 5);
552 	gva_t eaddr = kvmppc_get_gpr(vcpu, 6);
553 	gpa_t gp_to = (gpa_t) kvmppc_get_gpr(vcpu, 7);
554 	gpa_t gp_from = (gpa_t) kvmppc_get_gpr(vcpu, 8);
555 	void *buf;
556 	unsigned long n = kvmppc_get_gpr(vcpu, 9);
557 	bool is_load = !!gp_to;
558 	long rc;
559 
560 	if (gp_to && gp_from) /* One must be NULL to determine the direction */
561 		return H_PARAMETER;
562 
563 	if (eaddr & (0xFFFUL << 52))
564 		return H_PARAMETER;
565 
566 	buf = kzalloc(n, GFP_KERNEL);
567 	if (!buf)
568 		return H_NO_MEM;
569 
570 	gp = kvmhv_get_nested(vcpu->kvm, l1_lpid, false);
571 	if (!gp) {
572 		rc = H_PARAMETER;
573 		goto out_free;
574 	}
575 
576 	mutex_lock(&gp->tlb_lock);
577 
578 	if (is_load) {
579 		/* Load from the nested guest into our buffer */
580 		rc = __kvmhv_copy_tofrom_guest_radix(gp->shadow_lpid, pid,
581 						     eaddr, buf, NULL, n);
582 		if (rc)
583 			goto not_found;
584 
585 		/* Write what was loaded into our buffer back to the L1 guest */
586 		vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
587 		rc = kvm_vcpu_write_guest(vcpu, gp_to, buf, n);
588 		srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
589 		if (rc)
590 			goto not_found;
591 	} else {
592 		/* Load the data to be stored from the L1 guest into our buf */
593 		vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
594 		rc = kvm_vcpu_read_guest(vcpu, gp_from, buf, n);
595 		srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
596 		if (rc)
597 			goto not_found;
598 
599 		/* Store from our buffer into the nested guest */
600 		rc = __kvmhv_copy_tofrom_guest_radix(gp->shadow_lpid, pid,
601 						     eaddr, NULL, buf, n);
602 		if (rc)
603 			goto not_found;
604 	}
605 
606 out_unlock:
607 	mutex_unlock(&gp->tlb_lock);
608 	kvmhv_put_nested(gp);
609 out_free:
610 	kfree(buf);
611 	return rc;
612 not_found:
613 	rc = H_NOT_FOUND;
614 	goto out_unlock;
615 }
616 
617 /*
618  * Reload the partition table entry for a guest.
619  * Caller must hold gp->tlb_lock.
620  */
621 static void kvmhv_update_ptbl_cache(struct kvm_nested_guest *gp)
622 {
623 	int ret;
624 	struct patb_entry ptbl_entry;
625 	unsigned long ptbl_addr;
626 	struct kvm *kvm = gp->l1_host;
627 
628 	ret = -EFAULT;
629 	ptbl_addr = (kvm->arch.l1_ptcr & PRTB_MASK) + (gp->l1_lpid << 4);
630 	if (gp->l1_lpid < (1ul << ((kvm->arch.l1_ptcr & PRTS_MASK) + 8))) {
631 		int srcu_idx = srcu_read_lock(&kvm->srcu);
632 		ret = kvm_read_guest(kvm, ptbl_addr,
633 				     &ptbl_entry, sizeof(ptbl_entry));
634 		srcu_read_unlock(&kvm->srcu, srcu_idx);
635 	}
636 	if (ret) {
637 		gp->l1_gr_to_hr = 0;
638 		gp->process_table = 0;
639 	} else {
640 		gp->l1_gr_to_hr = be64_to_cpu(ptbl_entry.patb0);
641 		gp->process_table = be64_to_cpu(ptbl_entry.patb1);
642 	}
643 	kvmhv_set_nested_ptbl(gp);
644 }
645 
646 static struct kvm_nested_guest *kvmhv_alloc_nested(struct kvm *kvm, unsigned int lpid)
647 {
648 	struct kvm_nested_guest *gp;
649 	long shadow_lpid;
650 
651 	gp = kzalloc(sizeof(*gp), GFP_KERNEL);
652 	if (!gp)
653 		return NULL;
654 	gp->l1_host = kvm;
655 	gp->l1_lpid = lpid;
656 	mutex_init(&gp->tlb_lock);
657 	gp->shadow_pgtable = pgd_alloc(kvm->mm);
658 	if (!gp->shadow_pgtable)
659 		goto out_free;
660 	shadow_lpid = kvmppc_alloc_lpid();
661 	if (shadow_lpid < 0)
662 		goto out_free2;
663 	gp->shadow_lpid = shadow_lpid;
664 	gp->radix = 1;
665 
666 	memset(gp->prev_cpu, -1, sizeof(gp->prev_cpu));
667 
668 	return gp;
669 
670  out_free2:
671 	pgd_free(kvm->mm, gp->shadow_pgtable);
672  out_free:
673 	kfree(gp);
674 	return NULL;
675 }
676 
677 /*
678  * Free up any resources allocated for a nested guest.
679  */
680 static void kvmhv_release_nested(struct kvm_nested_guest *gp)
681 {
682 	struct kvm *kvm = gp->l1_host;
683 
684 	if (gp->shadow_pgtable) {
685 		/*
686 		 * No vcpu is using this struct and no call to
687 		 * kvmhv_get_nested can find this struct,
688 		 * so we don't need to hold kvm->mmu_lock.
689 		 */
690 		kvmppc_free_pgtable_radix(kvm, gp->shadow_pgtable,
691 					  gp->shadow_lpid);
692 		pgd_free(kvm->mm, gp->shadow_pgtable);
693 	}
694 	kvmhv_set_ptbl_entry(gp->shadow_lpid, 0, 0);
695 	kvmppc_free_lpid(gp->shadow_lpid);
696 	kfree(gp);
697 }
698 
699 static void kvmhv_remove_nested(struct kvm_nested_guest *gp)
700 {
701 	struct kvm *kvm = gp->l1_host;
702 	int lpid = gp->l1_lpid;
703 	long ref;
704 
705 	spin_lock(&kvm->mmu_lock);
706 	if (gp == kvm->arch.nested_guests[lpid]) {
707 		kvm->arch.nested_guests[lpid] = NULL;
708 		if (lpid == kvm->arch.max_nested_lpid) {
709 			while (--lpid >= 0 && !kvm->arch.nested_guests[lpid])
710 				;
711 			kvm->arch.max_nested_lpid = lpid;
712 		}
713 		--gp->refcnt;
714 	}
715 	ref = gp->refcnt;
716 	spin_unlock(&kvm->mmu_lock);
717 	if (ref == 0)
718 		kvmhv_release_nested(gp);
719 }
720 
721 /*
722  * Free up all nested resources allocated for this guest.
723  * This is called with no vcpus of the guest running, when
724  * switching the guest to HPT mode or when destroying the
725  * guest.
726  */
727 void kvmhv_release_all_nested(struct kvm *kvm)
728 {
729 	int i;
730 	struct kvm_nested_guest *gp;
731 	struct kvm_nested_guest *freelist = NULL;
732 	struct kvm_memory_slot *memslot;
733 	int srcu_idx;
734 
735 	spin_lock(&kvm->mmu_lock);
736 	for (i = 0; i <= kvm->arch.max_nested_lpid; i++) {
737 		gp = kvm->arch.nested_guests[i];
738 		if (!gp)
739 			continue;
740 		kvm->arch.nested_guests[i] = NULL;
741 		if (--gp->refcnt == 0) {
742 			gp->next = freelist;
743 			freelist = gp;
744 		}
745 	}
746 	kvm->arch.max_nested_lpid = -1;
747 	spin_unlock(&kvm->mmu_lock);
748 	while ((gp = freelist) != NULL) {
749 		freelist = gp->next;
750 		kvmhv_release_nested(gp);
751 	}
752 
753 	srcu_idx = srcu_read_lock(&kvm->srcu);
754 	kvm_for_each_memslot(memslot, kvm_memslots(kvm))
755 		kvmhv_free_memslot_nest_rmap(memslot);
756 	srcu_read_unlock(&kvm->srcu, srcu_idx);
757 }
758 
759 /* caller must hold gp->tlb_lock */
760 static void kvmhv_flush_nested(struct kvm_nested_guest *gp)
761 {
762 	struct kvm *kvm = gp->l1_host;
763 
764 	spin_lock(&kvm->mmu_lock);
765 	kvmppc_free_pgtable_radix(kvm, gp->shadow_pgtable, gp->shadow_lpid);
766 	spin_unlock(&kvm->mmu_lock);
767 	kvmhv_flush_lpid(gp->shadow_lpid);
768 	kvmhv_update_ptbl_cache(gp);
769 	if (gp->l1_gr_to_hr == 0)
770 		kvmhv_remove_nested(gp);
771 }
772 
773 struct kvm_nested_guest *kvmhv_get_nested(struct kvm *kvm, int l1_lpid,
774 					  bool create)
775 {
776 	struct kvm_nested_guest *gp, *newgp;
777 
778 	if (l1_lpid >= KVM_MAX_NESTED_GUESTS ||
779 	    l1_lpid >= (1ul << ((kvm->arch.l1_ptcr & PRTS_MASK) + 12 - 4)))
780 		return NULL;
781 
782 	spin_lock(&kvm->mmu_lock);
783 	gp = kvm->arch.nested_guests[l1_lpid];
784 	if (gp)
785 		++gp->refcnt;
786 	spin_unlock(&kvm->mmu_lock);
787 
788 	if (gp || !create)
789 		return gp;
790 
791 	newgp = kvmhv_alloc_nested(kvm, l1_lpid);
792 	if (!newgp)
793 		return NULL;
794 	spin_lock(&kvm->mmu_lock);
795 	if (kvm->arch.nested_guests[l1_lpid]) {
796 		/* someone else beat us to it */
797 		gp = kvm->arch.nested_guests[l1_lpid];
798 	} else {
799 		kvm->arch.nested_guests[l1_lpid] = newgp;
800 		++newgp->refcnt;
801 		gp = newgp;
802 		newgp = NULL;
803 		if (l1_lpid > kvm->arch.max_nested_lpid)
804 			kvm->arch.max_nested_lpid = l1_lpid;
805 	}
806 	++gp->refcnt;
807 	spin_unlock(&kvm->mmu_lock);
808 
809 	if (newgp)
810 		kvmhv_release_nested(newgp);
811 
812 	return gp;
813 }
814 
815 void kvmhv_put_nested(struct kvm_nested_guest *gp)
816 {
817 	struct kvm *kvm = gp->l1_host;
818 	long ref;
819 
820 	spin_lock(&kvm->mmu_lock);
821 	ref = --gp->refcnt;
822 	spin_unlock(&kvm->mmu_lock);
823 	if (ref == 0)
824 		kvmhv_release_nested(gp);
825 }
826 
827 static struct kvm_nested_guest *kvmhv_find_nested(struct kvm *kvm, int lpid)
828 {
829 	if (lpid > kvm->arch.max_nested_lpid)
830 		return NULL;
831 	return kvm->arch.nested_guests[lpid];
832 }
833 
834 pte_t *find_kvm_nested_guest_pte(struct kvm *kvm, unsigned long lpid,
835 				 unsigned long ea, unsigned *hshift)
836 {
837 	struct kvm_nested_guest *gp;
838 	pte_t *pte;
839 
840 	gp = kvmhv_find_nested(kvm, lpid);
841 	if (!gp)
842 		return NULL;
843 
844 	VM_WARN(!spin_is_locked(&kvm->mmu_lock),
845 		"%s called with kvm mmu_lock not held \n", __func__);
846 	pte = __find_linux_pte(gp->shadow_pgtable, ea, NULL, hshift);
847 
848 	return pte;
849 }
850 
851 static inline bool kvmhv_n_rmap_is_equal(u64 rmap_1, u64 rmap_2)
852 {
853 	return !((rmap_1 ^ rmap_2) & (RMAP_NESTED_LPID_MASK |
854 				       RMAP_NESTED_GPA_MASK));
855 }
856 
857 void kvmhv_insert_nest_rmap(struct kvm *kvm, unsigned long *rmapp,
858 			    struct rmap_nested **n_rmap)
859 {
860 	struct llist_node *entry = ((struct llist_head *) rmapp)->first;
861 	struct rmap_nested *cursor;
862 	u64 rmap, new_rmap = (*n_rmap)->rmap;
863 
864 	/* Are there any existing entries? */
865 	if (!(*rmapp)) {
866 		/* No -> use the rmap as a single entry */
867 		*rmapp = new_rmap | RMAP_NESTED_IS_SINGLE_ENTRY;
868 		return;
869 	}
870 
871 	/* Do any entries match what we're trying to insert? */
872 	for_each_nest_rmap_safe(cursor, entry, &rmap) {
873 		if (kvmhv_n_rmap_is_equal(rmap, new_rmap))
874 			return;
875 	}
876 
877 	/* Do we need to create a list or just add the new entry? */
878 	rmap = *rmapp;
879 	if (rmap & RMAP_NESTED_IS_SINGLE_ENTRY) /* Not previously a list */
880 		*rmapp = 0UL;
881 	llist_add(&((*n_rmap)->list), (struct llist_head *) rmapp);
882 	if (rmap & RMAP_NESTED_IS_SINGLE_ENTRY) /* Not previously a list */
883 		(*n_rmap)->list.next = (struct llist_node *) rmap;
884 
885 	/* Set NULL so not freed by caller */
886 	*n_rmap = NULL;
887 }
888 
889 static void kvmhv_update_nest_rmap_rc(struct kvm *kvm, u64 n_rmap,
890 				      unsigned long clr, unsigned long set,
891 				      unsigned long hpa, unsigned long mask)
892 {
893 	unsigned long gpa;
894 	unsigned int shift, lpid;
895 	pte_t *ptep;
896 
897 	gpa = n_rmap & RMAP_NESTED_GPA_MASK;
898 	lpid = (n_rmap & RMAP_NESTED_LPID_MASK) >> RMAP_NESTED_LPID_SHIFT;
899 
900 	/* Find the pte */
901 	ptep = find_kvm_nested_guest_pte(kvm, lpid, gpa, &shift);
902 	/*
903 	 * If the pte is present and the pfn is still the same, update the pte.
904 	 * If the pfn has changed then this is a stale rmap entry, the nested
905 	 * gpa actually points somewhere else now, and there is nothing to do.
906 	 * XXX A future optimisation would be to remove the rmap entry here.
907 	 */
908 	if (ptep && pte_present(*ptep) && ((pte_val(*ptep) & mask) == hpa)) {
909 		__radix_pte_update(ptep, clr, set);
910 		kvmppc_radix_tlbie_page(kvm, gpa, shift, lpid);
911 	}
912 }
913 
914 /*
915  * For a given list of rmap entries, update the rc bits in all ptes in shadow
916  * page tables for nested guests which are referenced by the rmap list.
917  */
918 void kvmhv_update_nest_rmap_rc_list(struct kvm *kvm, unsigned long *rmapp,
919 				    unsigned long clr, unsigned long set,
920 				    unsigned long hpa, unsigned long nbytes)
921 {
922 	struct llist_node *entry = ((struct llist_head *) rmapp)->first;
923 	struct rmap_nested *cursor;
924 	unsigned long rmap, mask;
925 
926 	if ((clr | set) & ~(_PAGE_DIRTY | _PAGE_ACCESSED))
927 		return;
928 
929 	mask = PTE_RPN_MASK & ~(nbytes - 1);
930 	hpa &= mask;
931 
932 	for_each_nest_rmap_safe(cursor, entry, &rmap)
933 		kvmhv_update_nest_rmap_rc(kvm, rmap, clr, set, hpa, mask);
934 }
935 
936 static void kvmhv_remove_nest_rmap(struct kvm *kvm, u64 n_rmap,
937 				   unsigned long hpa, unsigned long mask)
938 {
939 	struct kvm_nested_guest *gp;
940 	unsigned long gpa;
941 	unsigned int shift, lpid;
942 	pte_t *ptep;
943 
944 	gpa = n_rmap & RMAP_NESTED_GPA_MASK;
945 	lpid = (n_rmap & RMAP_NESTED_LPID_MASK) >> RMAP_NESTED_LPID_SHIFT;
946 	gp = kvmhv_find_nested(kvm, lpid);
947 	if (!gp)
948 		return;
949 
950 	/* Find and invalidate the pte */
951 	ptep = find_kvm_nested_guest_pte(kvm, lpid, gpa, &shift);
952 	/* Don't spuriously invalidate ptes if the pfn has changed */
953 	if (ptep && pte_present(*ptep) && ((pte_val(*ptep) & mask) == hpa))
954 		kvmppc_unmap_pte(kvm, ptep, gpa, shift, NULL, gp->shadow_lpid);
955 }
956 
957 static void kvmhv_remove_nest_rmap_list(struct kvm *kvm, unsigned long *rmapp,
958 					unsigned long hpa, unsigned long mask)
959 {
960 	struct llist_node *entry = llist_del_all((struct llist_head *) rmapp);
961 	struct rmap_nested *cursor;
962 	unsigned long rmap;
963 
964 	for_each_nest_rmap_safe(cursor, entry, &rmap) {
965 		kvmhv_remove_nest_rmap(kvm, rmap, hpa, mask);
966 		kfree(cursor);
967 	}
968 }
969 
970 /* called with kvm->mmu_lock held */
971 void kvmhv_remove_nest_rmap_range(struct kvm *kvm,
972 				  const struct kvm_memory_slot *memslot,
973 				  unsigned long gpa, unsigned long hpa,
974 				  unsigned long nbytes)
975 {
976 	unsigned long gfn, end_gfn;
977 	unsigned long addr_mask;
978 
979 	if (!memslot)
980 		return;
981 	gfn = (gpa >> PAGE_SHIFT) - memslot->base_gfn;
982 	end_gfn = gfn + (nbytes >> PAGE_SHIFT);
983 
984 	addr_mask = PTE_RPN_MASK & ~(nbytes - 1);
985 	hpa &= addr_mask;
986 
987 	for (; gfn < end_gfn; gfn++) {
988 		unsigned long *rmap = &memslot->arch.rmap[gfn];
989 		kvmhv_remove_nest_rmap_list(kvm, rmap, hpa, addr_mask);
990 	}
991 }
992 
993 static void kvmhv_free_memslot_nest_rmap(struct kvm_memory_slot *free)
994 {
995 	unsigned long page;
996 
997 	for (page = 0; page < free->npages; page++) {
998 		unsigned long rmap, *rmapp = &free->arch.rmap[page];
999 		struct rmap_nested *cursor;
1000 		struct llist_node *entry;
1001 
1002 		entry = llist_del_all((struct llist_head *) rmapp);
1003 		for_each_nest_rmap_safe(cursor, entry, &rmap)
1004 			kfree(cursor);
1005 	}
1006 }
1007 
1008 static bool kvmhv_invalidate_shadow_pte(struct kvm_vcpu *vcpu,
1009 					struct kvm_nested_guest *gp,
1010 					long gpa, int *shift_ret)
1011 {
1012 	struct kvm *kvm = vcpu->kvm;
1013 	bool ret = false;
1014 	pte_t *ptep;
1015 	int shift;
1016 
1017 	spin_lock(&kvm->mmu_lock);
1018 	ptep = find_kvm_nested_guest_pte(kvm, gp->l1_lpid, gpa, &shift);
1019 	if (!shift)
1020 		shift = PAGE_SHIFT;
1021 	if (ptep && pte_present(*ptep)) {
1022 		kvmppc_unmap_pte(kvm, ptep, gpa, shift, NULL, gp->shadow_lpid);
1023 		ret = true;
1024 	}
1025 	spin_unlock(&kvm->mmu_lock);
1026 
1027 	if (shift_ret)
1028 		*shift_ret = shift;
1029 	return ret;
1030 }
1031 
1032 static inline int get_ric(unsigned int instr)
1033 {
1034 	return (instr >> 18) & 0x3;
1035 }
1036 
1037 static inline int get_prs(unsigned int instr)
1038 {
1039 	return (instr >> 17) & 0x1;
1040 }
1041 
1042 static inline int get_r(unsigned int instr)
1043 {
1044 	return (instr >> 16) & 0x1;
1045 }
1046 
1047 static inline int get_lpid(unsigned long r_val)
1048 {
1049 	return r_val & 0xffffffff;
1050 }
1051 
1052 static inline int get_is(unsigned long r_val)
1053 {
1054 	return (r_val >> 10) & 0x3;
1055 }
1056 
1057 static inline int get_ap(unsigned long r_val)
1058 {
1059 	return (r_val >> 5) & 0x7;
1060 }
1061 
1062 static inline long get_epn(unsigned long r_val)
1063 {
1064 	return r_val >> 12;
1065 }
1066 
1067 static int kvmhv_emulate_tlbie_tlb_addr(struct kvm_vcpu *vcpu, int lpid,
1068 					int ap, long epn)
1069 {
1070 	struct kvm *kvm = vcpu->kvm;
1071 	struct kvm_nested_guest *gp;
1072 	long npages;
1073 	int shift, shadow_shift;
1074 	unsigned long addr;
1075 
1076 	shift = ap_to_shift(ap);
1077 	addr = epn << 12;
1078 	if (shift < 0)
1079 		/* Invalid ap encoding */
1080 		return -EINVAL;
1081 
1082 	addr &= ~((1UL << shift) - 1);
1083 	npages = 1UL << (shift - PAGE_SHIFT);
1084 
1085 	gp = kvmhv_get_nested(kvm, lpid, false);
1086 	if (!gp) /* No such guest -> nothing to do */
1087 		return 0;
1088 	mutex_lock(&gp->tlb_lock);
1089 
1090 	/* There may be more than one host page backing this single guest pte */
1091 	do {
1092 		kvmhv_invalidate_shadow_pte(vcpu, gp, addr, &shadow_shift);
1093 
1094 		npages -= 1UL << (shadow_shift - PAGE_SHIFT);
1095 		addr += 1UL << shadow_shift;
1096 	} while (npages > 0);
1097 
1098 	mutex_unlock(&gp->tlb_lock);
1099 	kvmhv_put_nested(gp);
1100 	return 0;
1101 }
1102 
1103 static void kvmhv_emulate_tlbie_lpid(struct kvm_vcpu *vcpu,
1104 				     struct kvm_nested_guest *gp, int ric)
1105 {
1106 	struct kvm *kvm = vcpu->kvm;
1107 
1108 	mutex_lock(&gp->tlb_lock);
1109 	switch (ric) {
1110 	case 0:
1111 		/* Invalidate TLB */
1112 		spin_lock(&kvm->mmu_lock);
1113 		kvmppc_free_pgtable_radix(kvm, gp->shadow_pgtable,
1114 					  gp->shadow_lpid);
1115 		kvmhv_flush_lpid(gp->shadow_lpid);
1116 		spin_unlock(&kvm->mmu_lock);
1117 		break;
1118 	case 1:
1119 		/*
1120 		 * Invalidate PWC
1121 		 * We don't cache this -> nothing to do
1122 		 */
1123 		break;
1124 	case 2:
1125 		/* Invalidate TLB, PWC and caching of partition table entries */
1126 		kvmhv_flush_nested(gp);
1127 		break;
1128 	default:
1129 		break;
1130 	}
1131 	mutex_unlock(&gp->tlb_lock);
1132 }
1133 
1134 static void kvmhv_emulate_tlbie_all_lpid(struct kvm_vcpu *vcpu, int ric)
1135 {
1136 	struct kvm *kvm = vcpu->kvm;
1137 	struct kvm_nested_guest *gp;
1138 	int i;
1139 
1140 	spin_lock(&kvm->mmu_lock);
1141 	for (i = 0; i <= kvm->arch.max_nested_lpid; i++) {
1142 		gp = kvm->arch.nested_guests[i];
1143 		if (gp) {
1144 			spin_unlock(&kvm->mmu_lock);
1145 			kvmhv_emulate_tlbie_lpid(vcpu, gp, ric);
1146 			spin_lock(&kvm->mmu_lock);
1147 		}
1148 	}
1149 	spin_unlock(&kvm->mmu_lock);
1150 }
1151 
1152 static int kvmhv_emulate_priv_tlbie(struct kvm_vcpu *vcpu, unsigned int instr,
1153 				    unsigned long rsval, unsigned long rbval)
1154 {
1155 	struct kvm *kvm = vcpu->kvm;
1156 	struct kvm_nested_guest *gp;
1157 	int r, ric, prs, is, ap;
1158 	int lpid;
1159 	long epn;
1160 	int ret = 0;
1161 
1162 	ric = get_ric(instr);
1163 	prs = get_prs(instr);
1164 	r = get_r(instr);
1165 	lpid = get_lpid(rsval);
1166 	is = get_is(rbval);
1167 
1168 	/*
1169 	 * These cases are invalid and are not handled:
1170 	 * r   != 1 -> Only radix supported
1171 	 * prs == 1 -> Not HV privileged
1172 	 * ric == 3 -> No cluster bombs for radix
1173 	 * is  == 1 -> Partition scoped translations not associated with pid
1174 	 * (!is) && (ric == 1 || ric == 2) -> Not supported by ISA
1175 	 */
1176 	if ((!r) || (prs) || (ric == 3) || (is == 1) ||
1177 	    ((!is) && (ric == 1 || ric == 2)))
1178 		return -EINVAL;
1179 
1180 	switch (is) {
1181 	case 0:
1182 		/*
1183 		 * We know ric == 0
1184 		 * Invalidate TLB for a given target address
1185 		 */
1186 		epn = get_epn(rbval);
1187 		ap = get_ap(rbval);
1188 		ret = kvmhv_emulate_tlbie_tlb_addr(vcpu, lpid, ap, epn);
1189 		break;
1190 	case 2:
1191 		/* Invalidate matching LPID */
1192 		gp = kvmhv_get_nested(kvm, lpid, false);
1193 		if (gp) {
1194 			kvmhv_emulate_tlbie_lpid(vcpu, gp, ric);
1195 			kvmhv_put_nested(gp);
1196 		}
1197 		break;
1198 	case 3:
1199 		/* Invalidate ALL LPIDs */
1200 		kvmhv_emulate_tlbie_all_lpid(vcpu, ric);
1201 		break;
1202 	default:
1203 		ret = -EINVAL;
1204 		break;
1205 	}
1206 
1207 	return ret;
1208 }
1209 
1210 /*
1211  * This handles the H_TLB_INVALIDATE hcall.
1212  * Parameters are (r4) tlbie instruction code, (r5) rS contents,
1213  * (r6) rB contents.
1214  */
1215 long kvmhv_do_nested_tlbie(struct kvm_vcpu *vcpu)
1216 {
1217 	int ret;
1218 
1219 	ret = kvmhv_emulate_priv_tlbie(vcpu, kvmppc_get_gpr(vcpu, 4),
1220 			kvmppc_get_gpr(vcpu, 5), kvmppc_get_gpr(vcpu, 6));
1221 	if (ret)
1222 		return H_PARAMETER;
1223 	return H_SUCCESS;
1224 }
1225 
1226 static long do_tlb_invalidate_nested_all(struct kvm_vcpu *vcpu,
1227 					 unsigned long lpid, unsigned long ric)
1228 {
1229 	struct kvm *kvm = vcpu->kvm;
1230 	struct kvm_nested_guest *gp;
1231 
1232 	gp = kvmhv_get_nested(kvm, lpid, false);
1233 	if (gp) {
1234 		kvmhv_emulate_tlbie_lpid(vcpu, gp, ric);
1235 		kvmhv_put_nested(gp);
1236 	}
1237 	return H_SUCCESS;
1238 }
1239 
1240 /*
1241  * Number of pages above which we invalidate the entire LPID rather than
1242  * flush individual pages.
1243  */
1244 static unsigned long tlb_range_flush_page_ceiling __read_mostly = 33;
1245 
1246 static long do_tlb_invalidate_nested_tlb(struct kvm_vcpu *vcpu,
1247 					 unsigned long lpid,
1248 					 unsigned long pg_sizes,
1249 					 unsigned long start,
1250 					 unsigned long end)
1251 {
1252 	int ret = H_P4;
1253 	unsigned long addr, nr_pages;
1254 	struct mmu_psize_def *def;
1255 	unsigned long psize, ap, page_size;
1256 	bool flush_lpid;
1257 
1258 	for (psize = 0; psize < MMU_PAGE_COUNT; psize++) {
1259 		def = &mmu_psize_defs[psize];
1260 		if (!(pg_sizes & def->h_rpt_pgsize))
1261 			continue;
1262 
1263 		nr_pages = (end - start) >> def->shift;
1264 		flush_lpid = nr_pages > tlb_range_flush_page_ceiling;
1265 		if (flush_lpid)
1266 			return do_tlb_invalidate_nested_all(vcpu, lpid,
1267 							RIC_FLUSH_TLB);
1268 		addr = start;
1269 		ap = mmu_get_ap(psize);
1270 		page_size = 1UL << def->shift;
1271 		do {
1272 			ret = kvmhv_emulate_tlbie_tlb_addr(vcpu, lpid, ap,
1273 						   get_epn(addr));
1274 			if (ret)
1275 				return H_P4;
1276 			addr += page_size;
1277 		} while (addr < end);
1278 	}
1279 	return ret;
1280 }
1281 
1282 /*
1283  * Performs partition-scoped invalidations for nested guests
1284  * as part of H_RPT_INVALIDATE hcall.
1285  */
1286 long do_h_rpt_invalidate_pat(struct kvm_vcpu *vcpu, unsigned long lpid,
1287 			     unsigned long type, unsigned long pg_sizes,
1288 			     unsigned long start, unsigned long end)
1289 {
1290 	/*
1291 	 * If L2 lpid isn't valid, we need to return H_PARAMETER.
1292 	 *
1293 	 * However, nested KVM issues a L2 lpid flush call when creating
1294 	 * partition table entries for L2. This happens even before the
1295 	 * corresponding shadow lpid is created in HV which happens in
1296 	 * H_ENTER_NESTED call. Since we can't differentiate this case from
1297 	 * the invalid case, we ignore such flush requests and return success.
1298 	 */
1299 	if (!kvmhv_find_nested(vcpu->kvm, lpid))
1300 		return H_SUCCESS;
1301 
1302 	/*
1303 	 * A flush all request can be handled by a full lpid flush only.
1304 	 */
1305 	if ((type & H_RPTI_TYPE_NESTED_ALL) == H_RPTI_TYPE_NESTED_ALL)
1306 		return do_tlb_invalidate_nested_all(vcpu, lpid, RIC_FLUSH_ALL);
1307 
1308 	/*
1309 	 * We don't need to handle a PWC flush like process table here,
1310 	 * because intermediate partition scoped table in nested guest doesn't
1311 	 * really have PWC. Only level we have PWC is in L0 and for nested
1312 	 * invalidate at L0 we always do kvm_flush_lpid() which does
1313 	 * radix__flush_all_lpid(). For range invalidate at any level, we
1314 	 * are not removing the higher level page tables and hence there is
1315 	 * no PWC invalidate needed.
1316 	 *
1317 	 * if (type & H_RPTI_TYPE_PWC) {
1318 	 *	ret = do_tlb_invalidate_nested_all(vcpu, lpid, RIC_FLUSH_PWC);
1319 	 *	if (ret)
1320 	 *		return H_P4;
1321 	 * }
1322 	 */
1323 
1324 	if (start == 0 && end == -1)
1325 		return do_tlb_invalidate_nested_all(vcpu, lpid, RIC_FLUSH_TLB);
1326 
1327 	if (type & H_RPTI_TYPE_TLB)
1328 		return do_tlb_invalidate_nested_tlb(vcpu, lpid, pg_sizes,
1329 						    start, end);
1330 	return H_SUCCESS;
1331 }
1332 
1333 /* Used to convert a nested guest real address to a L1 guest real address */
1334 static int kvmhv_translate_addr_nested(struct kvm_vcpu *vcpu,
1335 				       struct kvm_nested_guest *gp,
1336 				       unsigned long n_gpa, unsigned long dsisr,
1337 				       struct kvmppc_pte *gpte_p)
1338 {
1339 	u64 fault_addr, flags = dsisr & DSISR_ISSTORE;
1340 	int ret;
1341 
1342 	ret = kvmppc_mmu_walk_radix_tree(vcpu, n_gpa, gpte_p, gp->l1_gr_to_hr,
1343 					 &fault_addr);
1344 
1345 	if (ret) {
1346 		/* We didn't find a pte */
1347 		if (ret == -EINVAL) {
1348 			/* Unsupported mmu config */
1349 			flags |= DSISR_UNSUPP_MMU;
1350 		} else if (ret == -ENOENT) {
1351 			/* No translation found */
1352 			flags |= DSISR_NOHPTE;
1353 		} else if (ret == -EFAULT) {
1354 			/* Couldn't access L1 real address */
1355 			flags |= DSISR_PRTABLE_FAULT;
1356 			vcpu->arch.fault_gpa = fault_addr;
1357 		} else {
1358 			/* Unknown error */
1359 			return ret;
1360 		}
1361 		goto forward_to_l1;
1362 	} else {
1363 		/* We found a pte -> check permissions */
1364 		if (dsisr & DSISR_ISSTORE) {
1365 			/* Can we write? */
1366 			if (!gpte_p->may_write) {
1367 				flags |= DSISR_PROTFAULT;
1368 				goto forward_to_l1;
1369 			}
1370 		} else if (vcpu->arch.trap == BOOK3S_INTERRUPT_H_INST_STORAGE) {
1371 			/* Can we execute? */
1372 			if (!gpte_p->may_execute) {
1373 				flags |= SRR1_ISI_N_G_OR_CIP;
1374 				goto forward_to_l1;
1375 			}
1376 		} else {
1377 			/* Can we read? */
1378 			if (!gpte_p->may_read && !gpte_p->may_write) {
1379 				flags |= DSISR_PROTFAULT;
1380 				goto forward_to_l1;
1381 			}
1382 		}
1383 	}
1384 
1385 	return 0;
1386 
1387 forward_to_l1:
1388 	vcpu->arch.fault_dsisr = flags;
1389 	if (vcpu->arch.trap == BOOK3S_INTERRUPT_H_INST_STORAGE) {
1390 		vcpu->arch.shregs.msr &= SRR1_MSR_BITS;
1391 		vcpu->arch.shregs.msr |= flags;
1392 	}
1393 	return RESUME_HOST;
1394 }
1395 
1396 static long kvmhv_handle_nested_set_rc(struct kvm_vcpu *vcpu,
1397 				       struct kvm_nested_guest *gp,
1398 				       unsigned long n_gpa,
1399 				       struct kvmppc_pte gpte,
1400 				       unsigned long dsisr)
1401 {
1402 	struct kvm *kvm = vcpu->kvm;
1403 	bool writing = !!(dsisr & DSISR_ISSTORE);
1404 	u64 pgflags;
1405 	long ret;
1406 
1407 	/* Are the rc bits set in the L1 partition scoped pte? */
1408 	pgflags = _PAGE_ACCESSED;
1409 	if (writing)
1410 		pgflags |= _PAGE_DIRTY;
1411 	if (pgflags & ~gpte.rc)
1412 		return RESUME_HOST;
1413 
1414 	spin_lock(&kvm->mmu_lock);
1415 	/* Set the rc bit in the pte of our (L0) pgtable for the L1 guest */
1416 	ret = kvmppc_hv_handle_set_rc(kvm, false, writing,
1417 				      gpte.raddr, kvm->arch.lpid);
1418 	if (!ret) {
1419 		ret = -EINVAL;
1420 		goto out_unlock;
1421 	}
1422 
1423 	/* Set the rc bit in the pte of the shadow_pgtable for the nest guest */
1424 	ret = kvmppc_hv_handle_set_rc(kvm, true, writing,
1425 				      n_gpa, gp->l1_lpid);
1426 	if (!ret)
1427 		ret = -EINVAL;
1428 	else
1429 		ret = 0;
1430 
1431 out_unlock:
1432 	spin_unlock(&kvm->mmu_lock);
1433 	return ret;
1434 }
1435 
1436 static inline int kvmppc_radix_level_to_shift(int level)
1437 {
1438 	switch (level) {
1439 	case 2:
1440 		return PUD_SHIFT;
1441 	case 1:
1442 		return PMD_SHIFT;
1443 	default:
1444 		return PAGE_SHIFT;
1445 	}
1446 }
1447 
1448 static inline int kvmppc_radix_shift_to_level(int shift)
1449 {
1450 	if (shift == PUD_SHIFT)
1451 		return 2;
1452 	if (shift == PMD_SHIFT)
1453 		return 1;
1454 	if (shift == PAGE_SHIFT)
1455 		return 0;
1456 	WARN_ON_ONCE(1);
1457 	return 0;
1458 }
1459 
1460 /* called with gp->tlb_lock held */
1461 static long int __kvmhv_nested_page_fault(struct kvm_vcpu *vcpu,
1462 					  struct kvm_nested_guest *gp)
1463 {
1464 	struct kvm *kvm = vcpu->kvm;
1465 	struct kvm_memory_slot *memslot;
1466 	struct rmap_nested *n_rmap;
1467 	struct kvmppc_pte gpte;
1468 	pte_t pte, *pte_p;
1469 	unsigned long mmu_seq;
1470 	unsigned long dsisr = vcpu->arch.fault_dsisr;
1471 	unsigned long ea = vcpu->arch.fault_dar;
1472 	unsigned long *rmapp;
1473 	unsigned long n_gpa, gpa, gfn, perm = 0UL;
1474 	unsigned int shift, l1_shift, level;
1475 	bool writing = !!(dsisr & DSISR_ISSTORE);
1476 	bool kvm_ro = false;
1477 	long int ret;
1478 
1479 	if (!gp->l1_gr_to_hr) {
1480 		kvmhv_update_ptbl_cache(gp);
1481 		if (!gp->l1_gr_to_hr)
1482 			return RESUME_HOST;
1483 	}
1484 
1485 	/* Convert the nested guest real address into a L1 guest real address */
1486 
1487 	n_gpa = vcpu->arch.fault_gpa & ~0xF000000000000FFFULL;
1488 	if (!(dsisr & DSISR_PRTABLE_FAULT))
1489 		n_gpa |= ea & 0xFFF;
1490 	ret = kvmhv_translate_addr_nested(vcpu, gp, n_gpa, dsisr, &gpte);
1491 
1492 	/*
1493 	 * If the hardware found a translation but we don't now have a usable
1494 	 * translation in the l1 partition-scoped tree, remove the shadow pte
1495 	 * and let the guest retry.
1496 	 */
1497 	if (ret == RESUME_HOST &&
1498 	    (dsisr & (DSISR_PROTFAULT | DSISR_BADACCESS | DSISR_NOEXEC_OR_G |
1499 		      DSISR_BAD_COPYPASTE)))
1500 		goto inval;
1501 	if (ret)
1502 		return ret;
1503 
1504 	/* Failed to set the reference/change bits */
1505 	if (dsisr & DSISR_SET_RC) {
1506 		ret = kvmhv_handle_nested_set_rc(vcpu, gp, n_gpa, gpte, dsisr);
1507 		if (ret == RESUME_HOST)
1508 			return ret;
1509 		if (ret)
1510 			goto inval;
1511 		dsisr &= ~DSISR_SET_RC;
1512 		if (!(dsisr & (DSISR_BAD_FAULT_64S | DSISR_NOHPTE |
1513 			       DSISR_PROTFAULT)))
1514 			return RESUME_GUEST;
1515 	}
1516 
1517 	/*
1518 	 * We took an HISI or HDSI while we were running a nested guest which
1519 	 * means we have no partition scoped translation for that. This means
1520 	 * we need to insert a pte for the mapping into our shadow_pgtable.
1521 	 */
1522 
1523 	l1_shift = gpte.page_shift;
1524 	if (l1_shift < PAGE_SHIFT) {
1525 		/* We don't support l1 using a page size smaller than our own */
1526 		pr_err("KVM: L1 guest page shift (%d) less than our own (%d)\n",
1527 			l1_shift, PAGE_SHIFT);
1528 		return -EINVAL;
1529 	}
1530 	gpa = gpte.raddr;
1531 	gfn = gpa >> PAGE_SHIFT;
1532 
1533 	/* 1. Get the corresponding host memslot */
1534 
1535 	memslot = gfn_to_memslot(kvm, gfn);
1536 	if (!memslot || (memslot->flags & KVM_MEMSLOT_INVALID)) {
1537 		if (dsisr & (DSISR_PRTABLE_FAULT | DSISR_BADACCESS)) {
1538 			/* unusual error -> reflect to the guest as a DSI */
1539 			kvmppc_core_queue_data_storage(vcpu, ea, dsisr);
1540 			return RESUME_GUEST;
1541 		}
1542 
1543 		/* passthrough of emulated MMIO case */
1544 		return kvmppc_hv_emulate_mmio(vcpu, gpa, ea, writing);
1545 	}
1546 	if (memslot->flags & KVM_MEM_READONLY) {
1547 		if (writing) {
1548 			/* Give the guest a DSI */
1549 			kvmppc_core_queue_data_storage(vcpu, ea,
1550 					DSISR_ISSTORE | DSISR_PROTFAULT);
1551 			return RESUME_GUEST;
1552 		}
1553 		kvm_ro = true;
1554 	}
1555 
1556 	/* 2. Find the host pte for this L1 guest real address */
1557 
1558 	/* Used to check for invalidations in progress */
1559 	mmu_seq = kvm->mmu_notifier_seq;
1560 	smp_rmb();
1561 
1562 	/* See if can find translation in our partition scoped tables for L1 */
1563 	pte = __pte(0);
1564 	spin_lock(&kvm->mmu_lock);
1565 	pte_p = find_kvm_secondary_pte(kvm, gpa, &shift);
1566 	if (!shift)
1567 		shift = PAGE_SHIFT;
1568 	if (pte_p)
1569 		pte = *pte_p;
1570 	spin_unlock(&kvm->mmu_lock);
1571 
1572 	if (!pte_present(pte) || (writing && !(pte_val(pte) & _PAGE_WRITE))) {
1573 		/* No suitable pte found -> try to insert a mapping */
1574 		ret = kvmppc_book3s_instantiate_page(vcpu, gpa, memslot,
1575 					writing, kvm_ro, &pte, &level);
1576 		if (ret == -EAGAIN)
1577 			return RESUME_GUEST;
1578 		else if (ret)
1579 			return ret;
1580 		shift = kvmppc_radix_level_to_shift(level);
1581 	}
1582 	/* Align gfn to the start of the page */
1583 	gfn = (gpa & ~((1UL << shift) - 1)) >> PAGE_SHIFT;
1584 
1585 	/* 3. Compute the pte we need to insert for nest_gpa -> host r_addr */
1586 
1587 	/* The permissions is the combination of the host and l1 guest ptes */
1588 	perm |= gpte.may_read ? 0UL : _PAGE_READ;
1589 	perm |= gpte.may_write ? 0UL : _PAGE_WRITE;
1590 	perm |= gpte.may_execute ? 0UL : _PAGE_EXEC;
1591 	/* Only set accessed/dirty (rc) bits if set in host and l1 guest ptes */
1592 	perm |= (gpte.rc & _PAGE_ACCESSED) ? 0UL : _PAGE_ACCESSED;
1593 	perm |= ((gpte.rc & _PAGE_DIRTY) && writing) ? 0UL : _PAGE_DIRTY;
1594 	pte = __pte(pte_val(pte) & ~perm);
1595 
1596 	/* What size pte can we insert? */
1597 	if (shift > l1_shift) {
1598 		u64 mask;
1599 		unsigned int actual_shift = PAGE_SHIFT;
1600 		if (PMD_SHIFT < l1_shift)
1601 			actual_shift = PMD_SHIFT;
1602 		mask = (1UL << shift) - (1UL << actual_shift);
1603 		pte = __pte(pte_val(pte) | (gpa & mask));
1604 		shift = actual_shift;
1605 	}
1606 	level = kvmppc_radix_shift_to_level(shift);
1607 	n_gpa &= ~((1UL << shift) - 1);
1608 
1609 	/* 4. Insert the pte into our shadow_pgtable */
1610 
1611 	n_rmap = kzalloc(sizeof(*n_rmap), GFP_KERNEL);
1612 	if (!n_rmap)
1613 		return RESUME_GUEST; /* Let the guest try again */
1614 	n_rmap->rmap = (n_gpa & RMAP_NESTED_GPA_MASK) |
1615 		(((unsigned long) gp->l1_lpid) << RMAP_NESTED_LPID_SHIFT);
1616 	rmapp = &memslot->arch.rmap[gfn - memslot->base_gfn];
1617 	ret = kvmppc_create_pte(kvm, gp->shadow_pgtable, pte, n_gpa, level,
1618 				mmu_seq, gp->shadow_lpid, rmapp, &n_rmap);
1619 	kfree(n_rmap);
1620 	if (ret == -EAGAIN)
1621 		ret = RESUME_GUEST;	/* Let the guest try again */
1622 
1623 	return ret;
1624 
1625  inval:
1626 	kvmhv_invalidate_shadow_pte(vcpu, gp, n_gpa, NULL);
1627 	return RESUME_GUEST;
1628 }
1629 
1630 long int kvmhv_nested_page_fault(struct kvm_vcpu *vcpu)
1631 {
1632 	struct kvm_nested_guest *gp = vcpu->arch.nested;
1633 	long int ret;
1634 
1635 	mutex_lock(&gp->tlb_lock);
1636 	ret = __kvmhv_nested_page_fault(vcpu, gp);
1637 	mutex_unlock(&gp->tlb_lock);
1638 	return ret;
1639 }
1640 
1641 int kvmhv_nested_next_lpid(struct kvm *kvm, int lpid)
1642 {
1643 	int ret = -1;
1644 
1645 	spin_lock(&kvm->mmu_lock);
1646 	while (++lpid <= kvm->arch.max_nested_lpid) {
1647 		if (kvm->arch.nested_guests[lpid]) {
1648 			ret = lpid;
1649 			break;
1650 		}
1651 	}
1652 	spin_unlock(&kvm->mmu_lock);
1653 	return ret;
1654 }
1655