xref: /openbmc/linux/arch/powerpc/kvm/book3s_hv.c (revision 99a15348)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright 2011 Paul Mackerras, IBM Corp. <paulus@au1.ibm.com>
4  * Copyright (C) 2009. SUSE Linux Products GmbH. All rights reserved.
5  *
6  * Authors:
7  *    Paul Mackerras <paulus@au1.ibm.com>
8  *    Alexander Graf <agraf@suse.de>
9  *    Kevin Wolf <mail@kevin-wolf.de>
10  *
11  * Description: KVM functions specific to running on Book 3S
12  * processors in hypervisor mode (specifically POWER7 and later).
13  *
14  * This file is derived from arch/powerpc/kvm/book3s.c,
15  * by Alexander Graf <agraf@suse.de>.
16  */
17 
18 #include <linux/kvm_host.h>
19 #include <linux/kernel.h>
20 #include <linux/err.h>
21 #include <linux/slab.h>
22 #include <linux/preempt.h>
23 #include <linux/sched/signal.h>
24 #include <linux/sched/stat.h>
25 #include <linux/delay.h>
26 #include <linux/export.h>
27 #include <linux/fs.h>
28 #include <linux/anon_inodes.h>
29 #include <linux/cpu.h>
30 #include <linux/cpumask.h>
31 #include <linux/spinlock.h>
32 #include <linux/page-flags.h>
33 #include <linux/srcu.h>
34 #include <linux/miscdevice.h>
35 #include <linux/debugfs.h>
36 #include <linux/gfp.h>
37 #include <linux/vmalloc.h>
38 #include <linux/highmem.h>
39 #include <linux/hugetlb.h>
40 #include <linux/kvm_irqfd.h>
41 #include <linux/irqbypass.h>
42 #include <linux/module.h>
43 #include <linux/compiler.h>
44 #include <linux/of.h>
45 
46 #include <asm/ftrace.h>
47 #include <asm/reg.h>
48 #include <asm/ppc-opcode.h>
49 #include <asm/asm-prototypes.h>
50 #include <asm/archrandom.h>
51 #include <asm/debug.h>
52 #include <asm/disassemble.h>
53 #include <asm/cputable.h>
54 #include <asm/cacheflush.h>
55 #include <linux/uaccess.h>
56 #include <asm/interrupt.h>
57 #include <asm/io.h>
58 #include <asm/kvm_ppc.h>
59 #include <asm/kvm_book3s.h>
60 #include <asm/mmu_context.h>
61 #include <asm/lppaca.h>
62 #include <asm/pmc.h>
63 #include <asm/processor.h>
64 #include <asm/cputhreads.h>
65 #include <asm/page.h>
66 #include <asm/hvcall.h>
67 #include <asm/switch_to.h>
68 #include <asm/smp.h>
69 #include <asm/dbell.h>
70 #include <asm/hmi.h>
71 #include <asm/pnv-pci.h>
72 #include <asm/mmu.h>
73 #include <asm/opal.h>
74 #include <asm/xics.h>
75 #include <asm/xive.h>
76 #include <asm/hw_breakpoint.h>
77 #include <asm/kvm_book3s_uvmem.h>
78 #include <asm/ultravisor.h>
79 #include <asm/dtl.h>
80 #include <asm/plpar_wrappers.h>
81 
82 #include "book3s.h"
83 #include "book3s_hv.h"
84 
85 #define CREATE_TRACE_POINTS
86 #include "trace_hv.h"
87 
88 /* #define EXIT_DEBUG */
89 /* #define EXIT_DEBUG_SIMPLE */
90 /* #define EXIT_DEBUG_INT */
91 
92 /* Used to indicate that a guest page fault needs to be handled */
93 #define RESUME_PAGE_FAULT	(RESUME_GUEST | RESUME_FLAG_ARCH1)
94 /* Used to indicate that a guest passthrough interrupt needs to be handled */
95 #define RESUME_PASSTHROUGH	(RESUME_GUEST | RESUME_FLAG_ARCH2)
96 
97 /* Used as a "null" value for timebase values */
98 #define TB_NIL	(~(u64)0)
99 
100 static DECLARE_BITMAP(default_enabled_hcalls, MAX_HCALL_OPCODE/4 + 1);
101 
102 static int dynamic_mt_modes = 6;
103 module_param(dynamic_mt_modes, int, 0644);
104 MODULE_PARM_DESC(dynamic_mt_modes, "Set of allowed dynamic micro-threading modes: 0 (= none), 2, 4, or 6 (= 2 or 4)");
105 static int target_smt_mode;
106 module_param(target_smt_mode, int, 0644);
107 MODULE_PARM_DESC(target_smt_mode, "Target threads per core (0 = max)");
108 
109 static bool one_vm_per_core;
110 module_param(one_vm_per_core, bool, S_IRUGO | S_IWUSR);
111 MODULE_PARM_DESC(one_vm_per_core, "Only run vCPUs from the same VM on a core (requires POWER8 or older)");
112 
113 #ifdef CONFIG_KVM_XICS
114 static const struct kernel_param_ops module_param_ops = {
115 	.set = param_set_int,
116 	.get = param_get_int,
117 };
118 
119 module_param_cb(kvm_irq_bypass, &module_param_ops, &kvm_irq_bypass, 0644);
120 MODULE_PARM_DESC(kvm_irq_bypass, "Bypass passthrough interrupt optimization");
121 
122 module_param_cb(h_ipi_redirect, &module_param_ops, &h_ipi_redirect, 0644);
123 MODULE_PARM_DESC(h_ipi_redirect, "Redirect H_IPI wakeup to a free host core");
124 #endif
125 
126 /* If set, guests are allowed to create and control nested guests */
127 static bool nested = true;
128 module_param(nested, bool, S_IRUGO | S_IWUSR);
129 MODULE_PARM_DESC(nested, "Enable nested virtualization (only on POWER9)");
130 
131 static int kvmppc_hv_setup_htab_rma(struct kvm_vcpu *vcpu);
132 
133 /*
134  * RWMR values for POWER8.  These control the rate at which PURR
135  * and SPURR count and should be set according to the number of
136  * online threads in the vcore being run.
137  */
138 #define RWMR_RPA_P8_1THREAD	0x164520C62609AECAUL
139 #define RWMR_RPA_P8_2THREAD	0x7FFF2908450D8DA9UL
140 #define RWMR_RPA_P8_3THREAD	0x164520C62609AECAUL
141 #define RWMR_RPA_P8_4THREAD	0x199A421245058DA9UL
142 #define RWMR_RPA_P8_5THREAD	0x164520C62609AECAUL
143 #define RWMR_RPA_P8_6THREAD	0x164520C62609AECAUL
144 #define RWMR_RPA_P8_7THREAD	0x164520C62609AECAUL
145 #define RWMR_RPA_P8_8THREAD	0x164520C62609AECAUL
146 
147 static unsigned long p8_rwmr_values[MAX_SMT_THREADS + 1] = {
148 	RWMR_RPA_P8_1THREAD,
149 	RWMR_RPA_P8_1THREAD,
150 	RWMR_RPA_P8_2THREAD,
151 	RWMR_RPA_P8_3THREAD,
152 	RWMR_RPA_P8_4THREAD,
153 	RWMR_RPA_P8_5THREAD,
154 	RWMR_RPA_P8_6THREAD,
155 	RWMR_RPA_P8_7THREAD,
156 	RWMR_RPA_P8_8THREAD,
157 };
158 
159 static inline struct kvm_vcpu *next_runnable_thread(struct kvmppc_vcore *vc,
160 		int *ip)
161 {
162 	int i = *ip;
163 	struct kvm_vcpu *vcpu;
164 
165 	while (++i < MAX_SMT_THREADS) {
166 		vcpu = READ_ONCE(vc->runnable_threads[i]);
167 		if (vcpu) {
168 			*ip = i;
169 			return vcpu;
170 		}
171 	}
172 	return NULL;
173 }
174 
175 /* Used to traverse the list of runnable threads for a given vcore */
176 #define for_each_runnable_thread(i, vcpu, vc) \
177 	for (i = -1; (vcpu = next_runnable_thread(vc, &i)); )
178 
179 static bool kvmppc_ipi_thread(int cpu)
180 {
181 	unsigned long msg = PPC_DBELL_TYPE(PPC_DBELL_SERVER);
182 
183 	/* If we're a nested hypervisor, fall back to ordinary IPIs for now */
184 	if (kvmhv_on_pseries())
185 		return false;
186 
187 	/* On POWER9 we can use msgsnd to IPI any cpu */
188 	if (cpu_has_feature(CPU_FTR_ARCH_300)) {
189 		msg |= get_hard_smp_processor_id(cpu);
190 		smp_mb();
191 		__asm__ __volatile__ (PPC_MSGSND(%0) : : "r" (msg));
192 		return true;
193 	}
194 
195 	/* On POWER8 for IPIs to threads in the same core, use msgsnd */
196 	if (cpu_has_feature(CPU_FTR_ARCH_207S)) {
197 		preempt_disable();
198 		if (cpu_first_thread_sibling(cpu) ==
199 		    cpu_first_thread_sibling(smp_processor_id())) {
200 			msg |= cpu_thread_in_core(cpu);
201 			smp_mb();
202 			__asm__ __volatile__ (PPC_MSGSND(%0) : : "r" (msg));
203 			preempt_enable();
204 			return true;
205 		}
206 		preempt_enable();
207 	}
208 
209 #if defined(CONFIG_PPC_ICP_NATIVE) && defined(CONFIG_SMP)
210 	if (cpu >= 0 && cpu < nr_cpu_ids) {
211 		if (paca_ptrs[cpu]->kvm_hstate.xics_phys) {
212 			xics_wake_cpu(cpu);
213 			return true;
214 		}
215 		opal_int_set_mfrr(get_hard_smp_processor_id(cpu), IPI_PRIORITY);
216 		return true;
217 	}
218 #endif
219 
220 	return false;
221 }
222 
223 static void kvmppc_fast_vcpu_kick_hv(struct kvm_vcpu *vcpu)
224 {
225 	int cpu;
226 	struct rcuwait *waitp;
227 
228 	waitp = kvm_arch_vcpu_get_wait(vcpu);
229 	if (rcuwait_wake_up(waitp))
230 		++vcpu->stat.generic.halt_wakeup;
231 
232 	cpu = READ_ONCE(vcpu->arch.thread_cpu);
233 	if (cpu >= 0 && kvmppc_ipi_thread(cpu))
234 		return;
235 
236 	/* CPU points to the first thread of the core */
237 	cpu = vcpu->cpu;
238 	if (cpu >= 0 && cpu < nr_cpu_ids && cpu_online(cpu))
239 		smp_send_reschedule(cpu);
240 }
241 
242 /*
243  * We use the vcpu_load/put functions to measure stolen time.
244  * Stolen time is counted as time when either the vcpu is able to
245  * run as part of a virtual core, but the task running the vcore
246  * is preempted or sleeping, or when the vcpu needs something done
247  * in the kernel by the task running the vcpu, but that task is
248  * preempted or sleeping.  Those two things have to be counted
249  * separately, since one of the vcpu tasks will take on the job
250  * of running the core, and the other vcpu tasks in the vcore will
251  * sleep waiting for it to do that, but that sleep shouldn't count
252  * as stolen time.
253  *
254  * Hence we accumulate stolen time when the vcpu can run as part of
255  * a vcore using vc->stolen_tb, and the stolen time when the vcpu
256  * needs its task to do other things in the kernel (for example,
257  * service a page fault) in busy_stolen.  We don't accumulate
258  * stolen time for a vcore when it is inactive, or for a vcpu
259  * when it is in state RUNNING or NOTREADY.  NOTREADY is a bit of
260  * a misnomer; it means that the vcpu task is not executing in
261  * the KVM_VCPU_RUN ioctl, i.e. it is in userspace or elsewhere in
262  * the kernel.  We don't have any way of dividing up that time
263  * between time that the vcpu is genuinely stopped, time that
264  * the task is actively working on behalf of the vcpu, and time
265  * that the task is preempted, so we don't count any of it as
266  * stolen.
267  *
268  * Updates to busy_stolen are protected by arch.tbacct_lock;
269  * updates to vc->stolen_tb are protected by the vcore->stoltb_lock
270  * lock.  The stolen times are measured in units of timebase ticks.
271  * (Note that the != TB_NIL checks below are purely defensive;
272  * they should never fail.)
273  */
274 
275 static void kvmppc_core_start_stolen(struct kvmppc_vcore *vc, u64 tb)
276 {
277 	unsigned long flags;
278 
279 	WARN_ON_ONCE(cpu_has_feature(CPU_FTR_ARCH_300));
280 
281 	spin_lock_irqsave(&vc->stoltb_lock, flags);
282 	vc->preempt_tb = tb;
283 	spin_unlock_irqrestore(&vc->stoltb_lock, flags);
284 }
285 
286 static void kvmppc_core_end_stolen(struct kvmppc_vcore *vc, u64 tb)
287 {
288 	unsigned long flags;
289 
290 	WARN_ON_ONCE(cpu_has_feature(CPU_FTR_ARCH_300));
291 
292 	spin_lock_irqsave(&vc->stoltb_lock, flags);
293 	if (vc->preempt_tb != TB_NIL) {
294 		vc->stolen_tb += tb - vc->preempt_tb;
295 		vc->preempt_tb = TB_NIL;
296 	}
297 	spin_unlock_irqrestore(&vc->stoltb_lock, flags);
298 }
299 
300 static void kvmppc_core_vcpu_load_hv(struct kvm_vcpu *vcpu, int cpu)
301 {
302 	struct kvmppc_vcore *vc = vcpu->arch.vcore;
303 	unsigned long flags;
304 	u64 now;
305 
306 	if (cpu_has_feature(CPU_FTR_ARCH_300))
307 		return;
308 
309 	now = mftb();
310 
311 	/*
312 	 * We can test vc->runner without taking the vcore lock,
313 	 * because only this task ever sets vc->runner to this
314 	 * vcpu, and once it is set to this vcpu, only this task
315 	 * ever sets it to NULL.
316 	 */
317 	if (vc->runner == vcpu && vc->vcore_state >= VCORE_SLEEPING)
318 		kvmppc_core_end_stolen(vc, now);
319 
320 	spin_lock_irqsave(&vcpu->arch.tbacct_lock, flags);
321 	if (vcpu->arch.state == KVMPPC_VCPU_BUSY_IN_HOST &&
322 	    vcpu->arch.busy_preempt != TB_NIL) {
323 		vcpu->arch.busy_stolen += now - vcpu->arch.busy_preempt;
324 		vcpu->arch.busy_preempt = TB_NIL;
325 	}
326 	spin_unlock_irqrestore(&vcpu->arch.tbacct_lock, flags);
327 }
328 
329 static void kvmppc_core_vcpu_put_hv(struct kvm_vcpu *vcpu)
330 {
331 	struct kvmppc_vcore *vc = vcpu->arch.vcore;
332 	unsigned long flags;
333 	u64 now;
334 
335 	if (cpu_has_feature(CPU_FTR_ARCH_300))
336 		return;
337 
338 	now = mftb();
339 
340 	if (vc->runner == vcpu && vc->vcore_state >= VCORE_SLEEPING)
341 		kvmppc_core_start_stolen(vc, now);
342 
343 	spin_lock_irqsave(&vcpu->arch.tbacct_lock, flags);
344 	if (vcpu->arch.state == KVMPPC_VCPU_BUSY_IN_HOST)
345 		vcpu->arch.busy_preempt = now;
346 	spin_unlock_irqrestore(&vcpu->arch.tbacct_lock, flags);
347 }
348 
349 static void kvmppc_set_pvr_hv(struct kvm_vcpu *vcpu, u32 pvr)
350 {
351 	vcpu->arch.pvr = pvr;
352 }
353 
354 /* Dummy value used in computing PCR value below */
355 #define PCR_ARCH_31    (PCR_ARCH_300 << 1)
356 
357 static int kvmppc_set_arch_compat(struct kvm_vcpu *vcpu, u32 arch_compat)
358 {
359 	unsigned long host_pcr_bit = 0, guest_pcr_bit = 0;
360 	struct kvmppc_vcore *vc = vcpu->arch.vcore;
361 
362 	/* We can (emulate) our own architecture version and anything older */
363 	if (cpu_has_feature(CPU_FTR_ARCH_31))
364 		host_pcr_bit = PCR_ARCH_31;
365 	else if (cpu_has_feature(CPU_FTR_ARCH_300))
366 		host_pcr_bit = PCR_ARCH_300;
367 	else if (cpu_has_feature(CPU_FTR_ARCH_207S))
368 		host_pcr_bit = PCR_ARCH_207;
369 	else if (cpu_has_feature(CPU_FTR_ARCH_206))
370 		host_pcr_bit = PCR_ARCH_206;
371 	else
372 		host_pcr_bit = PCR_ARCH_205;
373 
374 	/* Determine lowest PCR bit needed to run guest in given PVR level */
375 	guest_pcr_bit = host_pcr_bit;
376 	if (arch_compat) {
377 		switch (arch_compat) {
378 		case PVR_ARCH_205:
379 			guest_pcr_bit = PCR_ARCH_205;
380 			break;
381 		case PVR_ARCH_206:
382 		case PVR_ARCH_206p:
383 			guest_pcr_bit = PCR_ARCH_206;
384 			break;
385 		case PVR_ARCH_207:
386 			guest_pcr_bit = PCR_ARCH_207;
387 			break;
388 		case PVR_ARCH_300:
389 			guest_pcr_bit = PCR_ARCH_300;
390 			break;
391 		case PVR_ARCH_31:
392 			guest_pcr_bit = PCR_ARCH_31;
393 			break;
394 		default:
395 			return -EINVAL;
396 		}
397 	}
398 
399 	/* Check requested PCR bits don't exceed our capabilities */
400 	if (guest_pcr_bit > host_pcr_bit)
401 		return -EINVAL;
402 
403 	spin_lock(&vc->lock);
404 	vc->arch_compat = arch_compat;
405 	/*
406 	 * Set all PCR bits for which guest_pcr_bit <= bit < host_pcr_bit
407 	 * Also set all reserved PCR bits
408 	 */
409 	vc->pcr = (host_pcr_bit - guest_pcr_bit) | PCR_MASK;
410 	spin_unlock(&vc->lock);
411 
412 	return 0;
413 }
414 
415 static void kvmppc_dump_regs(struct kvm_vcpu *vcpu)
416 {
417 	int r;
418 
419 	pr_err("vcpu %p (%d):\n", vcpu, vcpu->vcpu_id);
420 	pr_err("pc  = %.16lx  msr = %.16llx  trap = %x\n",
421 	       vcpu->arch.regs.nip, vcpu->arch.shregs.msr, vcpu->arch.trap);
422 	for (r = 0; r < 16; ++r)
423 		pr_err("r%2d = %.16lx  r%d = %.16lx\n",
424 		       r, kvmppc_get_gpr(vcpu, r),
425 		       r+16, kvmppc_get_gpr(vcpu, r+16));
426 	pr_err("ctr = %.16lx  lr  = %.16lx\n",
427 	       vcpu->arch.regs.ctr, vcpu->arch.regs.link);
428 	pr_err("srr0 = %.16llx srr1 = %.16llx\n",
429 	       vcpu->arch.shregs.srr0, vcpu->arch.shregs.srr1);
430 	pr_err("sprg0 = %.16llx sprg1 = %.16llx\n",
431 	       vcpu->arch.shregs.sprg0, vcpu->arch.shregs.sprg1);
432 	pr_err("sprg2 = %.16llx sprg3 = %.16llx\n",
433 	       vcpu->arch.shregs.sprg2, vcpu->arch.shregs.sprg3);
434 	pr_err("cr = %.8lx  xer = %.16lx  dsisr = %.8x\n",
435 	       vcpu->arch.regs.ccr, vcpu->arch.regs.xer, vcpu->arch.shregs.dsisr);
436 	pr_err("dar = %.16llx\n", vcpu->arch.shregs.dar);
437 	pr_err("fault dar = %.16lx dsisr = %.8x\n",
438 	       vcpu->arch.fault_dar, vcpu->arch.fault_dsisr);
439 	pr_err("SLB (%d entries):\n", vcpu->arch.slb_max);
440 	for (r = 0; r < vcpu->arch.slb_max; ++r)
441 		pr_err("  ESID = %.16llx VSID = %.16llx\n",
442 		       vcpu->arch.slb[r].orige, vcpu->arch.slb[r].origv);
443 	pr_err("lpcr = %.16lx sdr1 = %.16lx last_inst = %.8x\n",
444 	       vcpu->arch.vcore->lpcr, vcpu->kvm->arch.sdr1,
445 	       vcpu->arch.last_inst);
446 }
447 
448 static struct kvm_vcpu *kvmppc_find_vcpu(struct kvm *kvm, int id)
449 {
450 	return kvm_get_vcpu_by_id(kvm, id);
451 }
452 
453 static void init_vpa(struct kvm_vcpu *vcpu, struct lppaca *vpa)
454 {
455 	vpa->__old_status |= LPPACA_OLD_SHARED_PROC;
456 	vpa->yield_count = cpu_to_be32(1);
457 }
458 
459 static int set_vpa(struct kvm_vcpu *vcpu, struct kvmppc_vpa *v,
460 		   unsigned long addr, unsigned long len)
461 {
462 	/* check address is cacheline aligned */
463 	if (addr & (L1_CACHE_BYTES - 1))
464 		return -EINVAL;
465 	spin_lock(&vcpu->arch.vpa_update_lock);
466 	if (v->next_gpa != addr || v->len != len) {
467 		v->next_gpa = addr;
468 		v->len = addr ? len : 0;
469 		v->update_pending = 1;
470 	}
471 	spin_unlock(&vcpu->arch.vpa_update_lock);
472 	return 0;
473 }
474 
475 /* Length for a per-processor buffer is passed in at offset 4 in the buffer */
476 struct reg_vpa {
477 	u32 dummy;
478 	union {
479 		__be16 hword;
480 		__be32 word;
481 	} length;
482 };
483 
484 static int vpa_is_registered(struct kvmppc_vpa *vpap)
485 {
486 	if (vpap->update_pending)
487 		return vpap->next_gpa != 0;
488 	return vpap->pinned_addr != NULL;
489 }
490 
491 static unsigned long do_h_register_vpa(struct kvm_vcpu *vcpu,
492 				       unsigned long flags,
493 				       unsigned long vcpuid, unsigned long vpa)
494 {
495 	struct kvm *kvm = vcpu->kvm;
496 	unsigned long len, nb;
497 	void *va;
498 	struct kvm_vcpu *tvcpu;
499 	int err;
500 	int subfunc;
501 	struct kvmppc_vpa *vpap;
502 
503 	tvcpu = kvmppc_find_vcpu(kvm, vcpuid);
504 	if (!tvcpu)
505 		return H_PARAMETER;
506 
507 	subfunc = (flags >> H_VPA_FUNC_SHIFT) & H_VPA_FUNC_MASK;
508 	if (subfunc == H_VPA_REG_VPA || subfunc == H_VPA_REG_DTL ||
509 	    subfunc == H_VPA_REG_SLB) {
510 		/* Registering new area - address must be cache-line aligned */
511 		if ((vpa & (L1_CACHE_BYTES - 1)) || !vpa)
512 			return H_PARAMETER;
513 
514 		/* convert logical addr to kernel addr and read length */
515 		va = kvmppc_pin_guest_page(kvm, vpa, &nb);
516 		if (va == NULL)
517 			return H_PARAMETER;
518 		if (subfunc == H_VPA_REG_VPA)
519 			len = be16_to_cpu(((struct reg_vpa *)va)->length.hword);
520 		else
521 			len = be32_to_cpu(((struct reg_vpa *)va)->length.word);
522 		kvmppc_unpin_guest_page(kvm, va, vpa, false);
523 
524 		/* Check length */
525 		if (len > nb || len < sizeof(struct reg_vpa))
526 			return H_PARAMETER;
527 	} else {
528 		vpa = 0;
529 		len = 0;
530 	}
531 
532 	err = H_PARAMETER;
533 	vpap = NULL;
534 	spin_lock(&tvcpu->arch.vpa_update_lock);
535 
536 	switch (subfunc) {
537 	case H_VPA_REG_VPA:		/* register VPA */
538 		/*
539 		 * The size of our lppaca is 1kB because of the way we align
540 		 * it for the guest to avoid crossing a 4kB boundary. We only
541 		 * use 640 bytes of the structure though, so we should accept
542 		 * clients that set a size of 640.
543 		 */
544 		BUILD_BUG_ON(sizeof(struct lppaca) != 640);
545 		if (len < sizeof(struct lppaca))
546 			break;
547 		vpap = &tvcpu->arch.vpa;
548 		err = 0;
549 		break;
550 
551 	case H_VPA_REG_DTL:		/* register DTL */
552 		if (len < sizeof(struct dtl_entry))
553 			break;
554 		len -= len % sizeof(struct dtl_entry);
555 
556 		/* Check that they have previously registered a VPA */
557 		err = H_RESOURCE;
558 		if (!vpa_is_registered(&tvcpu->arch.vpa))
559 			break;
560 
561 		vpap = &tvcpu->arch.dtl;
562 		err = 0;
563 		break;
564 
565 	case H_VPA_REG_SLB:		/* register SLB shadow buffer */
566 		/* Check that they have previously registered a VPA */
567 		err = H_RESOURCE;
568 		if (!vpa_is_registered(&tvcpu->arch.vpa))
569 			break;
570 
571 		vpap = &tvcpu->arch.slb_shadow;
572 		err = 0;
573 		break;
574 
575 	case H_VPA_DEREG_VPA:		/* deregister VPA */
576 		/* Check they don't still have a DTL or SLB buf registered */
577 		err = H_RESOURCE;
578 		if (vpa_is_registered(&tvcpu->arch.dtl) ||
579 		    vpa_is_registered(&tvcpu->arch.slb_shadow))
580 			break;
581 
582 		vpap = &tvcpu->arch.vpa;
583 		err = 0;
584 		break;
585 
586 	case H_VPA_DEREG_DTL:		/* deregister DTL */
587 		vpap = &tvcpu->arch.dtl;
588 		err = 0;
589 		break;
590 
591 	case H_VPA_DEREG_SLB:		/* deregister SLB shadow buffer */
592 		vpap = &tvcpu->arch.slb_shadow;
593 		err = 0;
594 		break;
595 	}
596 
597 	if (vpap) {
598 		vpap->next_gpa = vpa;
599 		vpap->len = len;
600 		vpap->update_pending = 1;
601 	}
602 
603 	spin_unlock(&tvcpu->arch.vpa_update_lock);
604 
605 	return err;
606 }
607 
608 static void kvmppc_update_vpa(struct kvm_vcpu *vcpu, struct kvmppc_vpa *vpap)
609 {
610 	struct kvm *kvm = vcpu->kvm;
611 	void *va;
612 	unsigned long nb;
613 	unsigned long gpa;
614 
615 	/*
616 	 * We need to pin the page pointed to by vpap->next_gpa,
617 	 * but we can't call kvmppc_pin_guest_page under the lock
618 	 * as it does get_user_pages() and down_read().  So we
619 	 * have to drop the lock, pin the page, then get the lock
620 	 * again and check that a new area didn't get registered
621 	 * in the meantime.
622 	 */
623 	for (;;) {
624 		gpa = vpap->next_gpa;
625 		spin_unlock(&vcpu->arch.vpa_update_lock);
626 		va = NULL;
627 		nb = 0;
628 		if (gpa)
629 			va = kvmppc_pin_guest_page(kvm, gpa, &nb);
630 		spin_lock(&vcpu->arch.vpa_update_lock);
631 		if (gpa == vpap->next_gpa)
632 			break;
633 		/* sigh... unpin that one and try again */
634 		if (va)
635 			kvmppc_unpin_guest_page(kvm, va, gpa, false);
636 	}
637 
638 	vpap->update_pending = 0;
639 	if (va && nb < vpap->len) {
640 		/*
641 		 * If it's now too short, it must be that userspace
642 		 * has changed the mappings underlying guest memory,
643 		 * so unregister the region.
644 		 */
645 		kvmppc_unpin_guest_page(kvm, va, gpa, false);
646 		va = NULL;
647 	}
648 	if (vpap->pinned_addr)
649 		kvmppc_unpin_guest_page(kvm, vpap->pinned_addr, vpap->gpa,
650 					vpap->dirty);
651 	vpap->gpa = gpa;
652 	vpap->pinned_addr = va;
653 	vpap->dirty = false;
654 	if (va)
655 		vpap->pinned_end = va + vpap->len;
656 }
657 
658 static void kvmppc_update_vpas(struct kvm_vcpu *vcpu)
659 {
660 	if (!(vcpu->arch.vpa.update_pending ||
661 	      vcpu->arch.slb_shadow.update_pending ||
662 	      vcpu->arch.dtl.update_pending))
663 		return;
664 
665 	spin_lock(&vcpu->arch.vpa_update_lock);
666 	if (vcpu->arch.vpa.update_pending) {
667 		kvmppc_update_vpa(vcpu, &vcpu->arch.vpa);
668 		if (vcpu->arch.vpa.pinned_addr)
669 			init_vpa(vcpu, vcpu->arch.vpa.pinned_addr);
670 	}
671 	if (vcpu->arch.dtl.update_pending) {
672 		kvmppc_update_vpa(vcpu, &vcpu->arch.dtl);
673 		vcpu->arch.dtl_ptr = vcpu->arch.dtl.pinned_addr;
674 		vcpu->arch.dtl_index = 0;
675 	}
676 	if (vcpu->arch.slb_shadow.update_pending)
677 		kvmppc_update_vpa(vcpu, &vcpu->arch.slb_shadow);
678 	spin_unlock(&vcpu->arch.vpa_update_lock);
679 }
680 
681 /*
682  * Return the accumulated stolen time for the vcore up until `now'.
683  * The caller should hold the vcore lock.
684  */
685 static u64 vcore_stolen_time(struct kvmppc_vcore *vc, u64 now)
686 {
687 	u64 p;
688 	unsigned long flags;
689 
690 	WARN_ON_ONCE(cpu_has_feature(CPU_FTR_ARCH_300));
691 
692 	spin_lock_irqsave(&vc->stoltb_lock, flags);
693 	p = vc->stolen_tb;
694 	if (vc->vcore_state != VCORE_INACTIVE &&
695 	    vc->preempt_tb != TB_NIL)
696 		p += now - vc->preempt_tb;
697 	spin_unlock_irqrestore(&vc->stoltb_lock, flags);
698 	return p;
699 }
700 
701 static void __kvmppc_create_dtl_entry(struct kvm_vcpu *vcpu,
702 					unsigned int pcpu, u64 now,
703 					unsigned long stolen)
704 {
705 	struct dtl_entry *dt;
706 	struct lppaca *vpa;
707 
708 	dt = vcpu->arch.dtl_ptr;
709 	vpa = vcpu->arch.vpa.pinned_addr;
710 
711 	if (!dt || !vpa)
712 		return;
713 
714 	dt->dispatch_reason = 7;
715 	dt->preempt_reason = 0;
716 	dt->processor_id = cpu_to_be16(pcpu + vcpu->arch.ptid);
717 	dt->enqueue_to_dispatch_time = cpu_to_be32(stolen);
718 	dt->ready_to_enqueue_time = 0;
719 	dt->waiting_to_ready_time = 0;
720 	dt->timebase = cpu_to_be64(now);
721 	dt->fault_addr = 0;
722 	dt->srr0 = cpu_to_be64(kvmppc_get_pc(vcpu));
723 	dt->srr1 = cpu_to_be64(vcpu->arch.shregs.msr);
724 
725 	++dt;
726 	if (dt == vcpu->arch.dtl.pinned_end)
727 		dt = vcpu->arch.dtl.pinned_addr;
728 	vcpu->arch.dtl_ptr = dt;
729 	/* order writing *dt vs. writing vpa->dtl_idx */
730 	smp_wmb();
731 	vpa->dtl_idx = cpu_to_be64(++vcpu->arch.dtl_index);
732 	vcpu->arch.dtl.dirty = true;
733 }
734 
735 static void kvmppc_create_dtl_entry(struct kvm_vcpu *vcpu,
736 				    struct kvmppc_vcore *vc)
737 {
738 	unsigned long stolen;
739 	unsigned long core_stolen;
740 	u64 now;
741 	unsigned long flags;
742 
743 	now = mftb();
744 
745 	core_stolen = vcore_stolen_time(vc, now);
746 	stolen = core_stolen - vcpu->arch.stolen_logged;
747 	vcpu->arch.stolen_logged = core_stolen;
748 	spin_lock_irqsave(&vcpu->arch.tbacct_lock, flags);
749 	stolen += vcpu->arch.busy_stolen;
750 	vcpu->arch.busy_stolen = 0;
751 	spin_unlock_irqrestore(&vcpu->arch.tbacct_lock, flags);
752 
753 	__kvmppc_create_dtl_entry(vcpu, vc->pcpu, now + vc->tb_offset, stolen);
754 }
755 
756 /* See if there is a doorbell interrupt pending for a vcpu */
757 static bool kvmppc_doorbell_pending(struct kvm_vcpu *vcpu)
758 {
759 	int thr;
760 	struct kvmppc_vcore *vc;
761 
762 	if (vcpu->arch.doorbell_request)
763 		return true;
764 	if (cpu_has_feature(CPU_FTR_ARCH_300))
765 		return false;
766 	/*
767 	 * Ensure that the read of vcore->dpdes comes after the read
768 	 * of vcpu->doorbell_request.  This barrier matches the
769 	 * smp_wmb() in kvmppc_guest_entry_inject().
770 	 */
771 	smp_rmb();
772 	vc = vcpu->arch.vcore;
773 	thr = vcpu->vcpu_id - vc->first_vcpuid;
774 	return !!(vc->dpdes & (1 << thr));
775 }
776 
777 static bool kvmppc_power8_compatible(struct kvm_vcpu *vcpu)
778 {
779 	if (vcpu->arch.vcore->arch_compat >= PVR_ARCH_207)
780 		return true;
781 	if ((!vcpu->arch.vcore->arch_compat) &&
782 	    cpu_has_feature(CPU_FTR_ARCH_207S))
783 		return true;
784 	return false;
785 }
786 
787 static int kvmppc_h_set_mode(struct kvm_vcpu *vcpu, unsigned long mflags,
788 			     unsigned long resource, unsigned long value1,
789 			     unsigned long value2)
790 {
791 	switch (resource) {
792 	case H_SET_MODE_RESOURCE_SET_CIABR:
793 		if (!kvmppc_power8_compatible(vcpu))
794 			return H_P2;
795 		if (value2)
796 			return H_P4;
797 		if (mflags)
798 			return H_UNSUPPORTED_FLAG_START;
799 		/* Guests can't breakpoint the hypervisor */
800 		if ((value1 & CIABR_PRIV) == CIABR_PRIV_HYPER)
801 			return H_P3;
802 		vcpu->arch.ciabr  = value1;
803 		return H_SUCCESS;
804 	case H_SET_MODE_RESOURCE_SET_DAWR0:
805 		if (!kvmppc_power8_compatible(vcpu))
806 			return H_P2;
807 		if (!ppc_breakpoint_available())
808 			return H_P2;
809 		if (mflags)
810 			return H_UNSUPPORTED_FLAG_START;
811 		if (value2 & DABRX_HYP)
812 			return H_P4;
813 		vcpu->arch.dawr0  = value1;
814 		vcpu->arch.dawrx0 = value2;
815 		return H_SUCCESS;
816 	case H_SET_MODE_RESOURCE_SET_DAWR1:
817 		if (!kvmppc_power8_compatible(vcpu))
818 			return H_P2;
819 		if (!ppc_breakpoint_available())
820 			return H_P2;
821 		if (!cpu_has_feature(CPU_FTR_DAWR1))
822 			return H_P2;
823 		if (!vcpu->kvm->arch.dawr1_enabled)
824 			return H_FUNCTION;
825 		if (mflags)
826 			return H_UNSUPPORTED_FLAG_START;
827 		if (value2 & DABRX_HYP)
828 			return H_P4;
829 		vcpu->arch.dawr1  = value1;
830 		vcpu->arch.dawrx1 = value2;
831 		return H_SUCCESS;
832 	case H_SET_MODE_RESOURCE_ADDR_TRANS_MODE:
833 		/*
834 		 * KVM does not support mflags=2 (AIL=2) and AIL=1 is reserved.
835 		 * Keep this in synch with kvmppc_filter_guest_lpcr_hv.
836 		 */
837 		if (cpu_has_feature(CPU_FTR_P9_RADIX_PREFETCH_BUG) &&
838 				kvmhv_vcpu_is_radix(vcpu) && mflags == 3)
839 			return H_UNSUPPORTED_FLAG_START;
840 		return H_TOO_HARD;
841 	default:
842 		return H_TOO_HARD;
843 	}
844 }
845 
846 /* Copy guest memory in place - must reside within a single memslot */
847 static int kvmppc_copy_guest(struct kvm *kvm, gpa_t to, gpa_t from,
848 				  unsigned long len)
849 {
850 	struct kvm_memory_slot *to_memslot = NULL;
851 	struct kvm_memory_slot *from_memslot = NULL;
852 	unsigned long to_addr, from_addr;
853 	int r;
854 
855 	/* Get HPA for from address */
856 	from_memslot = gfn_to_memslot(kvm, from >> PAGE_SHIFT);
857 	if (!from_memslot)
858 		return -EFAULT;
859 	if ((from + len) >= ((from_memslot->base_gfn + from_memslot->npages)
860 			     << PAGE_SHIFT))
861 		return -EINVAL;
862 	from_addr = gfn_to_hva_memslot(from_memslot, from >> PAGE_SHIFT);
863 	if (kvm_is_error_hva(from_addr))
864 		return -EFAULT;
865 	from_addr |= (from & (PAGE_SIZE - 1));
866 
867 	/* Get HPA for to address */
868 	to_memslot = gfn_to_memslot(kvm, to >> PAGE_SHIFT);
869 	if (!to_memslot)
870 		return -EFAULT;
871 	if ((to + len) >= ((to_memslot->base_gfn + to_memslot->npages)
872 			   << PAGE_SHIFT))
873 		return -EINVAL;
874 	to_addr = gfn_to_hva_memslot(to_memslot, to >> PAGE_SHIFT);
875 	if (kvm_is_error_hva(to_addr))
876 		return -EFAULT;
877 	to_addr |= (to & (PAGE_SIZE - 1));
878 
879 	/* Perform copy */
880 	r = raw_copy_in_user((void __user *)to_addr, (void __user *)from_addr,
881 			     len);
882 	if (r)
883 		return -EFAULT;
884 	mark_page_dirty(kvm, to >> PAGE_SHIFT);
885 	return 0;
886 }
887 
888 static long kvmppc_h_page_init(struct kvm_vcpu *vcpu, unsigned long flags,
889 			       unsigned long dest, unsigned long src)
890 {
891 	u64 pg_sz = SZ_4K;		/* 4K page size */
892 	u64 pg_mask = SZ_4K - 1;
893 	int ret;
894 
895 	/* Check for invalid flags (H_PAGE_SET_LOANED covers all CMO flags) */
896 	if (flags & ~(H_ICACHE_INVALIDATE | H_ICACHE_SYNCHRONIZE |
897 		      H_ZERO_PAGE | H_COPY_PAGE | H_PAGE_SET_LOANED))
898 		return H_PARAMETER;
899 
900 	/* dest (and src if copy_page flag set) must be page aligned */
901 	if ((dest & pg_mask) || ((flags & H_COPY_PAGE) && (src & pg_mask)))
902 		return H_PARAMETER;
903 
904 	/* zero and/or copy the page as determined by the flags */
905 	if (flags & H_COPY_PAGE) {
906 		ret = kvmppc_copy_guest(vcpu->kvm, dest, src, pg_sz);
907 		if (ret < 0)
908 			return H_PARAMETER;
909 	} else if (flags & H_ZERO_PAGE) {
910 		ret = kvm_clear_guest(vcpu->kvm, dest, pg_sz);
911 		if (ret < 0)
912 			return H_PARAMETER;
913 	}
914 
915 	/* We can ignore the remaining flags */
916 
917 	return H_SUCCESS;
918 }
919 
920 static int kvm_arch_vcpu_yield_to(struct kvm_vcpu *target)
921 {
922 	struct kvmppc_vcore *vcore = target->arch.vcore;
923 
924 	/*
925 	 * We expect to have been called by the real mode handler
926 	 * (kvmppc_rm_h_confer()) which would have directly returned
927 	 * H_SUCCESS if the source vcore wasn't idle (e.g. if it may
928 	 * have useful work to do and should not confer) so we don't
929 	 * recheck that here.
930 	 *
931 	 * In the case of the P9 single vcpu per vcore case, the real
932 	 * mode handler is not called but no other threads are in the
933 	 * source vcore.
934 	 */
935 	if (!cpu_has_feature(CPU_FTR_ARCH_300)) {
936 		spin_lock(&vcore->lock);
937 		if (target->arch.state == KVMPPC_VCPU_RUNNABLE &&
938 		    vcore->vcore_state != VCORE_INACTIVE &&
939 		    vcore->runner)
940 			target = vcore->runner;
941 		spin_unlock(&vcore->lock);
942 	}
943 
944 	return kvm_vcpu_yield_to(target);
945 }
946 
947 static int kvmppc_get_yield_count(struct kvm_vcpu *vcpu)
948 {
949 	int yield_count = 0;
950 	struct lppaca *lppaca;
951 
952 	spin_lock(&vcpu->arch.vpa_update_lock);
953 	lppaca = (struct lppaca *)vcpu->arch.vpa.pinned_addr;
954 	if (lppaca)
955 		yield_count = be32_to_cpu(lppaca->yield_count);
956 	spin_unlock(&vcpu->arch.vpa_update_lock);
957 	return yield_count;
958 }
959 
960 /*
961  * H_RPT_INVALIDATE hcall handler for nested guests.
962  *
963  * Handles only nested process-scoped invalidation requests in L0.
964  */
965 static int kvmppc_nested_h_rpt_invalidate(struct kvm_vcpu *vcpu)
966 {
967 	unsigned long type = kvmppc_get_gpr(vcpu, 6);
968 	unsigned long pid, pg_sizes, start, end;
969 
970 	/*
971 	 * The partition-scoped invalidations aren't handled here in L0.
972 	 */
973 	if (type & H_RPTI_TYPE_NESTED)
974 		return RESUME_HOST;
975 
976 	pid = kvmppc_get_gpr(vcpu, 4);
977 	pg_sizes = kvmppc_get_gpr(vcpu, 7);
978 	start = kvmppc_get_gpr(vcpu, 8);
979 	end = kvmppc_get_gpr(vcpu, 9);
980 
981 	do_h_rpt_invalidate_prt(pid, vcpu->arch.nested->shadow_lpid,
982 				type, pg_sizes, start, end);
983 
984 	kvmppc_set_gpr(vcpu, 3, H_SUCCESS);
985 	return RESUME_GUEST;
986 }
987 
988 static long kvmppc_h_rpt_invalidate(struct kvm_vcpu *vcpu,
989 				    unsigned long id, unsigned long target,
990 				    unsigned long type, unsigned long pg_sizes,
991 				    unsigned long start, unsigned long end)
992 {
993 	if (!kvm_is_radix(vcpu->kvm))
994 		return H_UNSUPPORTED;
995 
996 	if (end < start)
997 		return H_P5;
998 
999 	/*
1000 	 * Partition-scoped invalidation for nested guests.
1001 	 */
1002 	if (type & H_RPTI_TYPE_NESTED) {
1003 		if (!nesting_enabled(vcpu->kvm))
1004 			return H_FUNCTION;
1005 
1006 		/* Support only cores as target */
1007 		if (target != H_RPTI_TARGET_CMMU)
1008 			return H_P2;
1009 
1010 		return do_h_rpt_invalidate_pat(vcpu, id, type, pg_sizes,
1011 					       start, end);
1012 	}
1013 
1014 	/*
1015 	 * Process-scoped invalidation for L1 guests.
1016 	 */
1017 	do_h_rpt_invalidate_prt(id, vcpu->kvm->arch.lpid,
1018 				type, pg_sizes, start, end);
1019 	return H_SUCCESS;
1020 }
1021 
1022 int kvmppc_pseries_do_hcall(struct kvm_vcpu *vcpu)
1023 {
1024 	struct kvm *kvm = vcpu->kvm;
1025 	unsigned long req = kvmppc_get_gpr(vcpu, 3);
1026 	unsigned long target, ret = H_SUCCESS;
1027 	int yield_count;
1028 	struct kvm_vcpu *tvcpu;
1029 	int idx, rc;
1030 
1031 	if (req <= MAX_HCALL_OPCODE &&
1032 	    !test_bit(req/4, vcpu->kvm->arch.enabled_hcalls))
1033 		return RESUME_HOST;
1034 
1035 	switch (req) {
1036 	case H_REMOVE:
1037 		ret = kvmppc_h_remove(vcpu, kvmppc_get_gpr(vcpu, 4),
1038 					kvmppc_get_gpr(vcpu, 5),
1039 					kvmppc_get_gpr(vcpu, 6));
1040 		if (ret == H_TOO_HARD)
1041 			return RESUME_HOST;
1042 		break;
1043 	case H_ENTER:
1044 		ret = kvmppc_h_enter(vcpu, kvmppc_get_gpr(vcpu, 4),
1045 					kvmppc_get_gpr(vcpu, 5),
1046 					kvmppc_get_gpr(vcpu, 6),
1047 					kvmppc_get_gpr(vcpu, 7));
1048 		if (ret == H_TOO_HARD)
1049 			return RESUME_HOST;
1050 		break;
1051 	case H_READ:
1052 		ret = kvmppc_h_read(vcpu, kvmppc_get_gpr(vcpu, 4),
1053 					kvmppc_get_gpr(vcpu, 5));
1054 		if (ret == H_TOO_HARD)
1055 			return RESUME_HOST;
1056 		break;
1057 	case H_CLEAR_MOD:
1058 		ret = kvmppc_h_clear_mod(vcpu, kvmppc_get_gpr(vcpu, 4),
1059 					kvmppc_get_gpr(vcpu, 5));
1060 		if (ret == H_TOO_HARD)
1061 			return RESUME_HOST;
1062 		break;
1063 	case H_CLEAR_REF:
1064 		ret = kvmppc_h_clear_ref(vcpu, kvmppc_get_gpr(vcpu, 4),
1065 					kvmppc_get_gpr(vcpu, 5));
1066 		if (ret == H_TOO_HARD)
1067 			return RESUME_HOST;
1068 		break;
1069 	case H_PROTECT:
1070 		ret = kvmppc_h_protect(vcpu, kvmppc_get_gpr(vcpu, 4),
1071 					kvmppc_get_gpr(vcpu, 5),
1072 					kvmppc_get_gpr(vcpu, 6));
1073 		if (ret == H_TOO_HARD)
1074 			return RESUME_HOST;
1075 		break;
1076 	case H_BULK_REMOVE:
1077 		ret = kvmppc_h_bulk_remove(vcpu);
1078 		if (ret == H_TOO_HARD)
1079 			return RESUME_HOST;
1080 		break;
1081 
1082 	case H_CEDE:
1083 		break;
1084 	case H_PROD:
1085 		target = kvmppc_get_gpr(vcpu, 4);
1086 		tvcpu = kvmppc_find_vcpu(kvm, target);
1087 		if (!tvcpu) {
1088 			ret = H_PARAMETER;
1089 			break;
1090 		}
1091 		tvcpu->arch.prodded = 1;
1092 		smp_mb();
1093 		if (tvcpu->arch.ceded)
1094 			kvmppc_fast_vcpu_kick_hv(tvcpu);
1095 		break;
1096 	case H_CONFER:
1097 		target = kvmppc_get_gpr(vcpu, 4);
1098 		if (target == -1)
1099 			break;
1100 		tvcpu = kvmppc_find_vcpu(kvm, target);
1101 		if (!tvcpu) {
1102 			ret = H_PARAMETER;
1103 			break;
1104 		}
1105 		yield_count = kvmppc_get_gpr(vcpu, 5);
1106 		if (kvmppc_get_yield_count(tvcpu) != yield_count)
1107 			break;
1108 		kvm_arch_vcpu_yield_to(tvcpu);
1109 		break;
1110 	case H_REGISTER_VPA:
1111 		ret = do_h_register_vpa(vcpu, kvmppc_get_gpr(vcpu, 4),
1112 					kvmppc_get_gpr(vcpu, 5),
1113 					kvmppc_get_gpr(vcpu, 6));
1114 		break;
1115 	case H_RTAS:
1116 		if (list_empty(&kvm->arch.rtas_tokens))
1117 			return RESUME_HOST;
1118 
1119 		idx = srcu_read_lock(&kvm->srcu);
1120 		rc = kvmppc_rtas_hcall(vcpu);
1121 		srcu_read_unlock(&kvm->srcu, idx);
1122 
1123 		if (rc == -ENOENT)
1124 			return RESUME_HOST;
1125 		else if (rc == 0)
1126 			break;
1127 
1128 		/* Send the error out to userspace via KVM_RUN */
1129 		return rc;
1130 	case H_LOGICAL_CI_LOAD:
1131 		ret = kvmppc_h_logical_ci_load(vcpu);
1132 		if (ret == H_TOO_HARD)
1133 			return RESUME_HOST;
1134 		break;
1135 	case H_LOGICAL_CI_STORE:
1136 		ret = kvmppc_h_logical_ci_store(vcpu);
1137 		if (ret == H_TOO_HARD)
1138 			return RESUME_HOST;
1139 		break;
1140 	case H_SET_MODE:
1141 		ret = kvmppc_h_set_mode(vcpu, kvmppc_get_gpr(vcpu, 4),
1142 					kvmppc_get_gpr(vcpu, 5),
1143 					kvmppc_get_gpr(vcpu, 6),
1144 					kvmppc_get_gpr(vcpu, 7));
1145 		if (ret == H_TOO_HARD)
1146 			return RESUME_HOST;
1147 		break;
1148 	case H_XIRR:
1149 	case H_CPPR:
1150 	case H_EOI:
1151 	case H_IPI:
1152 	case H_IPOLL:
1153 	case H_XIRR_X:
1154 		if (kvmppc_xics_enabled(vcpu)) {
1155 			if (xics_on_xive()) {
1156 				ret = H_NOT_AVAILABLE;
1157 				return RESUME_GUEST;
1158 			}
1159 			ret = kvmppc_xics_hcall(vcpu, req);
1160 			break;
1161 		}
1162 		return RESUME_HOST;
1163 	case H_SET_DABR:
1164 		ret = kvmppc_h_set_dabr(vcpu, kvmppc_get_gpr(vcpu, 4));
1165 		break;
1166 	case H_SET_XDABR:
1167 		ret = kvmppc_h_set_xdabr(vcpu, kvmppc_get_gpr(vcpu, 4),
1168 						kvmppc_get_gpr(vcpu, 5));
1169 		break;
1170 #ifdef CONFIG_SPAPR_TCE_IOMMU
1171 	case H_GET_TCE:
1172 		ret = kvmppc_h_get_tce(vcpu, kvmppc_get_gpr(vcpu, 4),
1173 						kvmppc_get_gpr(vcpu, 5));
1174 		if (ret == H_TOO_HARD)
1175 			return RESUME_HOST;
1176 		break;
1177 	case H_PUT_TCE:
1178 		ret = kvmppc_h_put_tce(vcpu, kvmppc_get_gpr(vcpu, 4),
1179 						kvmppc_get_gpr(vcpu, 5),
1180 						kvmppc_get_gpr(vcpu, 6));
1181 		if (ret == H_TOO_HARD)
1182 			return RESUME_HOST;
1183 		break;
1184 	case H_PUT_TCE_INDIRECT:
1185 		ret = kvmppc_h_put_tce_indirect(vcpu, kvmppc_get_gpr(vcpu, 4),
1186 						kvmppc_get_gpr(vcpu, 5),
1187 						kvmppc_get_gpr(vcpu, 6),
1188 						kvmppc_get_gpr(vcpu, 7));
1189 		if (ret == H_TOO_HARD)
1190 			return RESUME_HOST;
1191 		break;
1192 	case H_STUFF_TCE:
1193 		ret = kvmppc_h_stuff_tce(vcpu, kvmppc_get_gpr(vcpu, 4),
1194 						kvmppc_get_gpr(vcpu, 5),
1195 						kvmppc_get_gpr(vcpu, 6),
1196 						kvmppc_get_gpr(vcpu, 7));
1197 		if (ret == H_TOO_HARD)
1198 			return RESUME_HOST;
1199 		break;
1200 #endif
1201 	case H_RANDOM:
1202 		if (!arch_get_random_seed_long(&vcpu->arch.regs.gpr[4]))
1203 			ret = H_HARDWARE;
1204 		break;
1205 	case H_RPT_INVALIDATE:
1206 		ret = kvmppc_h_rpt_invalidate(vcpu, kvmppc_get_gpr(vcpu, 4),
1207 					      kvmppc_get_gpr(vcpu, 5),
1208 					      kvmppc_get_gpr(vcpu, 6),
1209 					      kvmppc_get_gpr(vcpu, 7),
1210 					      kvmppc_get_gpr(vcpu, 8),
1211 					      kvmppc_get_gpr(vcpu, 9));
1212 		break;
1213 
1214 	case H_SET_PARTITION_TABLE:
1215 		ret = H_FUNCTION;
1216 		if (nesting_enabled(kvm))
1217 			ret = kvmhv_set_partition_table(vcpu);
1218 		break;
1219 	case H_ENTER_NESTED:
1220 		ret = H_FUNCTION;
1221 		if (!nesting_enabled(kvm))
1222 			break;
1223 		ret = kvmhv_enter_nested_guest(vcpu);
1224 		if (ret == H_INTERRUPT) {
1225 			kvmppc_set_gpr(vcpu, 3, 0);
1226 			vcpu->arch.hcall_needed = 0;
1227 			return -EINTR;
1228 		} else if (ret == H_TOO_HARD) {
1229 			kvmppc_set_gpr(vcpu, 3, 0);
1230 			vcpu->arch.hcall_needed = 0;
1231 			return RESUME_HOST;
1232 		}
1233 		break;
1234 	case H_TLB_INVALIDATE:
1235 		ret = H_FUNCTION;
1236 		if (nesting_enabled(kvm))
1237 			ret = kvmhv_do_nested_tlbie(vcpu);
1238 		break;
1239 	case H_COPY_TOFROM_GUEST:
1240 		ret = H_FUNCTION;
1241 		if (nesting_enabled(kvm))
1242 			ret = kvmhv_copy_tofrom_guest_nested(vcpu);
1243 		break;
1244 	case H_PAGE_INIT:
1245 		ret = kvmppc_h_page_init(vcpu, kvmppc_get_gpr(vcpu, 4),
1246 					 kvmppc_get_gpr(vcpu, 5),
1247 					 kvmppc_get_gpr(vcpu, 6));
1248 		break;
1249 	case H_SVM_PAGE_IN:
1250 		ret = H_UNSUPPORTED;
1251 		if (kvmppc_get_srr1(vcpu) & MSR_S)
1252 			ret = kvmppc_h_svm_page_in(kvm,
1253 						   kvmppc_get_gpr(vcpu, 4),
1254 						   kvmppc_get_gpr(vcpu, 5),
1255 						   kvmppc_get_gpr(vcpu, 6));
1256 		break;
1257 	case H_SVM_PAGE_OUT:
1258 		ret = H_UNSUPPORTED;
1259 		if (kvmppc_get_srr1(vcpu) & MSR_S)
1260 			ret = kvmppc_h_svm_page_out(kvm,
1261 						    kvmppc_get_gpr(vcpu, 4),
1262 						    kvmppc_get_gpr(vcpu, 5),
1263 						    kvmppc_get_gpr(vcpu, 6));
1264 		break;
1265 	case H_SVM_INIT_START:
1266 		ret = H_UNSUPPORTED;
1267 		if (kvmppc_get_srr1(vcpu) & MSR_S)
1268 			ret = kvmppc_h_svm_init_start(kvm);
1269 		break;
1270 	case H_SVM_INIT_DONE:
1271 		ret = H_UNSUPPORTED;
1272 		if (kvmppc_get_srr1(vcpu) & MSR_S)
1273 			ret = kvmppc_h_svm_init_done(kvm);
1274 		break;
1275 	case H_SVM_INIT_ABORT:
1276 		/*
1277 		 * Even if that call is made by the Ultravisor, the SSR1 value
1278 		 * is the guest context one, with the secure bit clear as it has
1279 		 * not yet been secured. So we can't check it here.
1280 		 * Instead the kvm->arch.secure_guest flag is checked inside
1281 		 * kvmppc_h_svm_init_abort().
1282 		 */
1283 		ret = kvmppc_h_svm_init_abort(kvm);
1284 		break;
1285 
1286 	default:
1287 		return RESUME_HOST;
1288 	}
1289 	WARN_ON_ONCE(ret == H_TOO_HARD);
1290 	kvmppc_set_gpr(vcpu, 3, ret);
1291 	vcpu->arch.hcall_needed = 0;
1292 	return RESUME_GUEST;
1293 }
1294 
1295 /*
1296  * Handle H_CEDE in the P9 path where we don't call the real-mode hcall
1297  * handlers in book3s_hv_rmhandlers.S.
1298  *
1299  * This has to be done early, not in kvmppc_pseries_do_hcall(), so
1300  * that the cede logic in kvmppc_run_single_vcpu() works properly.
1301  */
1302 static void kvmppc_cede(struct kvm_vcpu *vcpu)
1303 {
1304 	vcpu->arch.shregs.msr |= MSR_EE;
1305 	vcpu->arch.ceded = 1;
1306 	smp_mb();
1307 	if (vcpu->arch.prodded) {
1308 		vcpu->arch.prodded = 0;
1309 		smp_mb();
1310 		vcpu->arch.ceded = 0;
1311 	}
1312 }
1313 
1314 static int kvmppc_hcall_impl_hv(unsigned long cmd)
1315 {
1316 	switch (cmd) {
1317 	case H_CEDE:
1318 	case H_PROD:
1319 	case H_CONFER:
1320 	case H_REGISTER_VPA:
1321 	case H_SET_MODE:
1322 	case H_LOGICAL_CI_LOAD:
1323 	case H_LOGICAL_CI_STORE:
1324 #ifdef CONFIG_KVM_XICS
1325 	case H_XIRR:
1326 	case H_CPPR:
1327 	case H_EOI:
1328 	case H_IPI:
1329 	case H_IPOLL:
1330 	case H_XIRR_X:
1331 #endif
1332 	case H_PAGE_INIT:
1333 	case H_RPT_INVALIDATE:
1334 		return 1;
1335 	}
1336 
1337 	/* See if it's in the real-mode table */
1338 	return kvmppc_hcall_impl_hv_realmode(cmd);
1339 }
1340 
1341 static int kvmppc_emulate_debug_inst(struct kvm_vcpu *vcpu)
1342 {
1343 	u32 last_inst;
1344 
1345 	if (kvmppc_get_last_inst(vcpu, INST_GENERIC, &last_inst) !=
1346 					EMULATE_DONE) {
1347 		/*
1348 		 * Fetch failed, so return to guest and
1349 		 * try executing it again.
1350 		 */
1351 		return RESUME_GUEST;
1352 	}
1353 
1354 	if (last_inst == KVMPPC_INST_SW_BREAKPOINT) {
1355 		vcpu->run->exit_reason = KVM_EXIT_DEBUG;
1356 		vcpu->run->debug.arch.address = kvmppc_get_pc(vcpu);
1357 		return RESUME_HOST;
1358 	} else {
1359 		kvmppc_core_queue_program(vcpu, SRR1_PROGILL);
1360 		return RESUME_GUEST;
1361 	}
1362 }
1363 
1364 static void do_nothing(void *x)
1365 {
1366 }
1367 
1368 static unsigned long kvmppc_read_dpdes(struct kvm_vcpu *vcpu)
1369 {
1370 	int thr, cpu, pcpu, nthreads;
1371 	struct kvm_vcpu *v;
1372 	unsigned long dpdes;
1373 
1374 	nthreads = vcpu->kvm->arch.emul_smt_mode;
1375 	dpdes = 0;
1376 	cpu = vcpu->vcpu_id & ~(nthreads - 1);
1377 	for (thr = 0; thr < nthreads; ++thr, ++cpu) {
1378 		v = kvmppc_find_vcpu(vcpu->kvm, cpu);
1379 		if (!v)
1380 			continue;
1381 		/*
1382 		 * If the vcpu is currently running on a physical cpu thread,
1383 		 * interrupt it in order to pull it out of the guest briefly,
1384 		 * which will update its vcore->dpdes value.
1385 		 */
1386 		pcpu = READ_ONCE(v->cpu);
1387 		if (pcpu >= 0)
1388 			smp_call_function_single(pcpu, do_nothing, NULL, 1);
1389 		if (kvmppc_doorbell_pending(v))
1390 			dpdes |= 1 << thr;
1391 	}
1392 	return dpdes;
1393 }
1394 
1395 /*
1396  * On POWER9, emulate doorbell-related instructions in order to
1397  * give the guest the illusion of running on a multi-threaded core.
1398  * The instructions emulated are msgsndp, msgclrp, mfspr TIR,
1399  * and mfspr DPDES.
1400  */
1401 static int kvmppc_emulate_doorbell_instr(struct kvm_vcpu *vcpu)
1402 {
1403 	u32 inst, rb, thr;
1404 	unsigned long arg;
1405 	struct kvm *kvm = vcpu->kvm;
1406 	struct kvm_vcpu *tvcpu;
1407 
1408 	if (kvmppc_get_last_inst(vcpu, INST_GENERIC, &inst) != EMULATE_DONE)
1409 		return RESUME_GUEST;
1410 	if (get_op(inst) != 31)
1411 		return EMULATE_FAIL;
1412 	rb = get_rb(inst);
1413 	thr = vcpu->vcpu_id & (kvm->arch.emul_smt_mode - 1);
1414 	switch (get_xop(inst)) {
1415 	case OP_31_XOP_MSGSNDP:
1416 		arg = kvmppc_get_gpr(vcpu, rb);
1417 		if (((arg >> 27) & 0x1f) != PPC_DBELL_SERVER)
1418 			break;
1419 		arg &= 0x7f;
1420 		if (arg >= kvm->arch.emul_smt_mode)
1421 			break;
1422 		tvcpu = kvmppc_find_vcpu(kvm, vcpu->vcpu_id - thr + arg);
1423 		if (!tvcpu)
1424 			break;
1425 		if (!tvcpu->arch.doorbell_request) {
1426 			tvcpu->arch.doorbell_request = 1;
1427 			kvmppc_fast_vcpu_kick_hv(tvcpu);
1428 		}
1429 		break;
1430 	case OP_31_XOP_MSGCLRP:
1431 		arg = kvmppc_get_gpr(vcpu, rb);
1432 		if (((arg >> 27) & 0x1f) != PPC_DBELL_SERVER)
1433 			break;
1434 		vcpu->arch.vcore->dpdes = 0;
1435 		vcpu->arch.doorbell_request = 0;
1436 		break;
1437 	case OP_31_XOP_MFSPR:
1438 		switch (get_sprn(inst)) {
1439 		case SPRN_TIR:
1440 			arg = thr;
1441 			break;
1442 		case SPRN_DPDES:
1443 			arg = kvmppc_read_dpdes(vcpu);
1444 			break;
1445 		default:
1446 			return EMULATE_FAIL;
1447 		}
1448 		kvmppc_set_gpr(vcpu, get_rt(inst), arg);
1449 		break;
1450 	default:
1451 		return EMULATE_FAIL;
1452 	}
1453 	kvmppc_set_pc(vcpu, kvmppc_get_pc(vcpu) + 4);
1454 	return RESUME_GUEST;
1455 }
1456 
1457 /*
1458  * If the lppaca had pmcregs_in_use clear when we exited the guest, then
1459  * HFSCR_PM is cleared for next entry. If the guest then tries to access
1460  * the PMU SPRs, we get this facility unavailable interrupt. Putting HFSCR_PM
1461  * back in the guest HFSCR will cause the next entry to load the PMU SPRs and
1462  * allow the guest access to continue.
1463  */
1464 static int kvmppc_pmu_unavailable(struct kvm_vcpu *vcpu)
1465 {
1466 	if (!(vcpu->arch.hfscr_permitted & HFSCR_PM))
1467 		return EMULATE_FAIL;
1468 
1469 	vcpu->arch.hfscr |= HFSCR_PM;
1470 
1471 	return RESUME_GUEST;
1472 }
1473 
1474 static int kvmppc_ebb_unavailable(struct kvm_vcpu *vcpu)
1475 {
1476 	if (!(vcpu->arch.hfscr_permitted & HFSCR_EBB))
1477 		return EMULATE_FAIL;
1478 
1479 	vcpu->arch.hfscr |= HFSCR_EBB;
1480 
1481 	return RESUME_GUEST;
1482 }
1483 
1484 static int kvmppc_tm_unavailable(struct kvm_vcpu *vcpu)
1485 {
1486 	if (!(vcpu->arch.hfscr_permitted & HFSCR_TM))
1487 		return EMULATE_FAIL;
1488 
1489 	vcpu->arch.hfscr |= HFSCR_TM;
1490 
1491 	return RESUME_GUEST;
1492 }
1493 
1494 static int kvmppc_handle_exit_hv(struct kvm_vcpu *vcpu,
1495 				 struct task_struct *tsk)
1496 {
1497 	struct kvm_run *run = vcpu->run;
1498 	int r = RESUME_HOST;
1499 
1500 	vcpu->stat.sum_exits++;
1501 
1502 	/*
1503 	 * This can happen if an interrupt occurs in the last stages
1504 	 * of guest entry or the first stages of guest exit (i.e. after
1505 	 * setting paca->kvm_hstate.in_guest to KVM_GUEST_MODE_GUEST_HV
1506 	 * and before setting it to KVM_GUEST_MODE_HOST_HV).
1507 	 * That can happen due to a bug, or due to a machine check
1508 	 * occurring at just the wrong time.
1509 	 */
1510 	if (vcpu->arch.shregs.msr & MSR_HV) {
1511 		printk(KERN_EMERG "KVM trap in HV mode!\n");
1512 		printk(KERN_EMERG "trap=0x%x | pc=0x%lx | msr=0x%llx\n",
1513 			vcpu->arch.trap, kvmppc_get_pc(vcpu),
1514 			vcpu->arch.shregs.msr);
1515 		kvmppc_dump_regs(vcpu);
1516 		run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
1517 		run->hw.hardware_exit_reason = vcpu->arch.trap;
1518 		return RESUME_HOST;
1519 	}
1520 	run->exit_reason = KVM_EXIT_UNKNOWN;
1521 	run->ready_for_interrupt_injection = 1;
1522 	switch (vcpu->arch.trap) {
1523 	/* We're good on these - the host merely wanted to get our attention */
1524 	case BOOK3S_INTERRUPT_NESTED_HV_DECREMENTER:
1525 		WARN_ON_ONCE(1); /* Should never happen */
1526 		vcpu->arch.trap = BOOK3S_INTERRUPT_HV_DECREMENTER;
1527 		fallthrough;
1528 	case BOOK3S_INTERRUPT_HV_DECREMENTER:
1529 		vcpu->stat.dec_exits++;
1530 		r = RESUME_GUEST;
1531 		break;
1532 	case BOOK3S_INTERRUPT_EXTERNAL:
1533 	case BOOK3S_INTERRUPT_H_DOORBELL:
1534 	case BOOK3S_INTERRUPT_H_VIRT:
1535 		vcpu->stat.ext_intr_exits++;
1536 		r = RESUME_GUEST;
1537 		break;
1538 	/* SR/HMI/PMI are HV interrupts that host has handled. Resume guest.*/
1539 	case BOOK3S_INTERRUPT_HMI:
1540 	case BOOK3S_INTERRUPT_PERFMON:
1541 	case BOOK3S_INTERRUPT_SYSTEM_RESET:
1542 		r = RESUME_GUEST;
1543 		break;
1544 	case BOOK3S_INTERRUPT_MACHINE_CHECK: {
1545 		static DEFINE_RATELIMIT_STATE(rs, DEFAULT_RATELIMIT_INTERVAL,
1546 					      DEFAULT_RATELIMIT_BURST);
1547 		/*
1548 		 * Print the MCE event to host console. Ratelimit so the guest
1549 		 * can't flood the host log.
1550 		 */
1551 		if (__ratelimit(&rs))
1552 			machine_check_print_event_info(&vcpu->arch.mce_evt,false, true);
1553 
1554 		/*
1555 		 * If the guest can do FWNMI, exit to userspace so it can
1556 		 * deliver a FWNMI to the guest.
1557 		 * Otherwise we synthesize a machine check for the guest
1558 		 * so that it knows that the machine check occurred.
1559 		 */
1560 		if (!vcpu->kvm->arch.fwnmi_enabled) {
1561 			ulong flags = vcpu->arch.shregs.msr & 0x083c0000;
1562 			kvmppc_core_queue_machine_check(vcpu, flags);
1563 			r = RESUME_GUEST;
1564 			break;
1565 		}
1566 
1567 		/* Exit to guest with KVM_EXIT_NMI as exit reason */
1568 		run->exit_reason = KVM_EXIT_NMI;
1569 		run->hw.hardware_exit_reason = vcpu->arch.trap;
1570 		/* Clear out the old NMI status from run->flags */
1571 		run->flags &= ~KVM_RUN_PPC_NMI_DISP_MASK;
1572 		/* Now set the NMI status */
1573 		if (vcpu->arch.mce_evt.disposition == MCE_DISPOSITION_RECOVERED)
1574 			run->flags |= KVM_RUN_PPC_NMI_DISP_FULLY_RECOV;
1575 		else
1576 			run->flags |= KVM_RUN_PPC_NMI_DISP_NOT_RECOV;
1577 
1578 		r = RESUME_HOST;
1579 		break;
1580 	}
1581 	case BOOK3S_INTERRUPT_PROGRAM:
1582 	{
1583 		ulong flags;
1584 		/*
1585 		 * Normally program interrupts are delivered directly
1586 		 * to the guest by the hardware, but we can get here
1587 		 * as a result of a hypervisor emulation interrupt
1588 		 * (e40) getting turned into a 700 by BML RTAS.
1589 		 */
1590 		flags = vcpu->arch.shregs.msr & 0x1f0000ull;
1591 		kvmppc_core_queue_program(vcpu, flags);
1592 		r = RESUME_GUEST;
1593 		break;
1594 	}
1595 	case BOOK3S_INTERRUPT_SYSCALL:
1596 	{
1597 		int i;
1598 
1599 		if (unlikely(vcpu->arch.shregs.msr & MSR_PR)) {
1600 			/*
1601 			 * Guest userspace executed sc 1. This can only be
1602 			 * reached by the P9 path because the old path
1603 			 * handles this case in realmode hcall handlers.
1604 			 */
1605 			if (!kvmhv_vcpu_is_radix(vcpu)) {
1606 				/*
1607 				 * A guest could be running PR KVM, so this
1608 				 * may be a PR KVM hcall. It must be reflected
1609 				 * to the guest kernel as a sc interrupt.
1610 				 */
1611 				kvmppc_core_queue_syscall(vcpu);
1612 			} else {
1613 				/*
1614 				 * Radix guests can not run PR KVM or nested HV
1615 				 * hash guests which might run PR KVM, so this
1616 				 * is always a privilege fault. Send a program
1617 				 * check to guest kernel.
1618 				 */
1619 				kvmppc_core_queue_program(vcpu, SRR1_PROGPRIV);
1620 			}
1621 			r = RESUME_GUEST;
1622 			break;
1623 		}
1624 
1625 		/*
1626 		 * hcall - gather args and set exit_reason. This will next be
1627 		 * handled by kvmppc_pseries_do_hcall which may be able to deal
1628 		 * with it and resume guest, or may punt to userspace.
1629 		 */
1630 		run->papr_hcall.nr = kvmppc_get_gpr(vcpu, 3);
1631 		for (i = 0; i < 9; ++i)
1632 			run->papr_hcall.args[i] = kvmppc_get_gpr(vcpu, 4 + i);
1633 		run->exit_reason = KVM_EXIT_PAPR_HCALL;
1634 		vcpu->arch.hcall_needed = 1;
1635 		r = RESUME_HOST;
1636 		break;
1637 	}
1638 	/*
1639 	 * We get these next two if the guest accesses a page which it thinks
1640 	 * it has mapped but which is not actually present, either because
1641 	 * it is for an emulated I/O device or because the corresonding
1642 	 * host page has been paged out.
1643 	 *
1644 	 * Any other HDSI/HISI interrupts have been handled already for P7/8
1645 	 * guests. For POWER9 hash guests not using rmhandlers, basic hash
1646 	 * fault handling is done here.
1647 	 */
1648 	case BOOK3S_INTERRUPT_H_DATA_STORAGE: {
1649 		unsigned long vsid;
1650 		long err;
1651 
1652 		if (cpu_has_feature(CPU_FTR_P9_RADIX_PREFETCH_BUG) &&
1653 		    unlikely(vcpu->arch.fault_dsisr == HDSISR_CANARY)) {
1654 			r = RESUME_GUEST; /* Just retry if it's the canary */
1655 			break;
1656 		}
1657 
1658 		if (kvm_is_radix(vcpu->kvm) || !cpu_has_feature(CPU_FTR_ARCH_300)) {
1659 			/*
1660 			 * Radix doesn't require anything, and pre-ISAv3.0 hash
1661 			 * already attempted to handle this in rmhandlers. The
1662 			 * hash fault handling below is v3 only (it uses ASDR
1663 			 * via fault_gpa).
1664 			 */
1665 			r = RESUME_PAGE_FAULT;
1666 			break;
1667 		}
1668 
1669 		if (!(vcpu->arch.fault_dsisr & (DSISR_NOHPTE | DSISR_PROTFAULT))) {
1670 			kvmppc_core_queue_data_storage(vcpu,
1671 				vcpu->arch.fault_dar, vcpu->arch.fault_dsisr);
1672 			r = RESUME_GUEST;
1673 			break;
1674 		}
1675 
1676 		if (!(vcpu->arch.shregs.msr & MSR_DR))
1677 			vsid = vcpu->kvm->arch.vrma_slb_v;
1678 		else
1679 			vsid = vcpu->arch.fault_gpa;
1680 
1681 		err = kvmppc_hpte_hv_fault(vcpu, vcpu->arch.fault_dar,
1682 				vsid, vcpu->arch.fault_dsisr, true);
1683 		if (err == 0) {
1684 			r = RESUME_GUEST;
1685 		} else if (err == -1 || err == -2) {
1686 			r = RESUME_PAGE_FAULT;
1687 		} else {
1688 			kvmppc_core_queue_data_storage(vcpu,
1689 				vcpu->arch.fault_dar, err);
1690 			r = RESUME_GUEST;
1691 		}
1692 		break;
1693 	}
1694 	case BOOK3S_INTERRUPT_H_INST_STORAGE: {
1695 		unsigned long vsid;
1696 		long err;
1697 
1698 		vcpu->arch.fault_dar = kvmppc_get_pc(vcpu);
1699 		vcpu->arch.fault_dsisr = vcpu->arch.shregs.msr &
1700 			DSISR_SRR1_MATCH_64S;
1701 		if (kvm_is_radix(vcpu->kvm) || !cpu_has_feature(CPU_FTR_ARCH_300)) {
1702 			/*
1703 			 * Radix doesn't require anything, and pre-ISAv3.0 hash
1704 			 * already attempted to handle this in rmhandlers. The
1705 			 * hash fault handling below is v3 only (it uses ASDR
1706 			 * via fault_gpa).
1707 			 */
1708 			if (vcpu->arch.shregs.msr & HSRR1_HISI_WRITE)
1709 				vcpu->arch.fault_dsisr |= DSISR_ISSTORE;
1710 			r = RESUME_PAGE_FAULT;
1711 			break;
1712 		}
1713 
1714 		if (!(vcpu->arch.fault_dsisr & SRR1_ISI_NOPT)) {
1715 			kvmppc_core_queue_inst_storage(vcpu,
1716 				vcpu->arch.fault_dsisr);
1717 			r = RESUME_GUEST;
1718 			break;
1719 		}
1720 
1721 		if (!(vcpu->arch.shregs.msr & MSR_IR))
1722 			vsid = vcpu->kvm->arch.vrma_slb_v;
1723 		else
1724 			vsid = vcpu->arch.fault_gpa;
1725 
1726 		err = kvmppc_hpte_hv_fault(vcpu, vcpu->arch.fault_dar,
1727 				vsid, vcpu->arch.fault_dsisr, false);
1728 		if (err == 0) {
1729 			r = RESUME_GUEST;
1730 		} else if (err == -1) {
1731 			r = RESUME_PAGE_FAULT;
1732 		} else {
1733 			kvmppc_core_queue_inst_storage(vcpu, err);
1734 			r = RESUME_GUEST;
1735 		}
1736 		break;
1737 	}
1738 
1739 	/*
1740 	 * This occurs if the guest executes an illegal instruction.
1741 	 * If the guest debug is disabled, generate a program interrupt
1742 	 * to the guest. If guest debug is enabled, we need to check
1743 	 * whether the instruction is a software breakpoint instruction.
1744 	 * Accordingly return to Guest or Host.
1745 	 */
1746 	case BOOK3S_INTERRUPT_H_EMUL_ASSIST:
1747 		if (vcpu->arch.emul_inst != KVM_INST_FETCH_FAILED)
1748 			vcpu->arch.last_inst = kvmppc_need_byteswap(vcpu) ?
1749 				swab32(vcpu->arch.emul_inst) :
1750 				vcpu->arch.emul_inst;
1751 		if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP) {
1752 			r = kvmppc_emulate_debug_inst(vcpu);
1753 		} else {
1754 			kvmppc_core_queue_program(vcpu, SRR1_PROGILL);
1755 			r = RESUME_GUEST;
1756 		}
1757 		break;
1758 
1759 #ifdef CONFIG_PPC_TRANSACTIONAL_MEM
1760 	case BOOK3S_INTERRUPT_HV_SOFTPATCH:
1761 		/*
1762 		 * This occurs for various TM-related instructions that
1763 		 * we need to emulate on POWER9 DD2.2.  We have already
1764 		 * handled the cases where the guest was in real-suspend
1765 		 * mode and was transitioning to transactional state.
1766 		 */
1767 		r = kvmhv_p9_tm_emulation(vcpu);
1768 		if (r != -1)
1769 			break;
1770 		fallthrough; /* go to facility unavailable handler */
1771 #endif
1772 
1773 	/*
1774 	 * This occurs if the guest (kernel or userspace), does something that
1775 	 * is prohibited by HFSCR.
1776 	 * On POWER9, this could be a doorbell instruction that we need
1777 	 * to emulate.
1778 	 * Otherwise, we just generate a program interrupt to the guest.
1779 	 */
1780 	case BOOK3S_INTERRUPT_H_FAC_UNAVAIL: {
1781 		u64 cause = vcpu->arch.hfscr >> 56;
1782 
1783 		r = EMULATE_FAIL;
1784 		if (cpu_has_feature(CPU_FTR_ARCH_300)) {
1785 			if (cause == FSCR_MSGP_LG)
1786 				r = kvmppc_emulate_doorbell_instr(vcpu);
1787 			if (cause == FSCR_PM_LG)
1788 				r = kvmppc_pmu_unavailable(vcpu);
1789 			if (cause == FSCR_EBB_LG)
1790 				r = kvmppc_ebb_unavailable(vcpu);
1791 			if (cause == FSCR_TM_LG)
1792 				r = kvmppc_tm_unavailable(vcpu);
1793 		}
1794 		if (r == EMULATE_FAIL) {
1795 			kvmppc_core_queue_program(vcpu, SRR1_PROGILL);
1796 			r = RESUME_GUEST;
1797 		}
1798 		break;
1799 	}
1800 
1801 	case BOOK3S_INTERRUPT_HV_RM_HARD:
1802 		r = RESUME_PASSTHROUGH;
1803 		break;
1804 	default:
1805 		kvmppc_dump_regs(vcpu);
1806 		printk(KERN_EMERG "trap=0x%x | pc=0x%lx | msr=0x%llx\n",
1807 			vcpu->arch.trap, kvmppc_get_pc(vcpu),
1808 			vcpu->arch.shregs.msr);
1809 		run->hw.hardware_exit_reason = vcpu->arch.trap;
1810 		r = RESUME_HOST;
1811 		break;
1812 	}
1813 
1814 	return r;
1815 }
1816 
1817 static int kvmppc_handle_nested_exit(struct kvm_vcpu *vcpu)
1818 {
1819 	int r;
1820 	int srcu_idx;
1821 
1822 	vcpu->stat.sum_exits++;
1823 
1824 	/*
1825 	 * This can happen if an interrupt occurs in the last stages
1826 	 * of guest entry or the first stages of guest exit (i.e. after
1827 	 * setting paca->kvm_hstate.in_guest to KVM_GUEST_MODE_GUEST_HV
1828 	 * and before setting it to KVM_GUEST_MODE_HOST_HV).
1829 	 * That can happen due to a bug, or due to a machine check
1830 	 * occurring at just the wrong time.
1831 	 */
1832 	if (vcpu->arch.shregs.msr & MSR_HV) {
1833 		pr_emerg("KVM trap in HV mode while nested!\n");
1834 		pr_emerg("trap=0x%x | pc=0x%lx | msr=0x%llx\n",
1835 			 vcpu->arch.trap, kvmppc_get_pc(vcpu),
1836 			 vcpu->arch.shregs.msr);
1837 		kvmppc_dump_regs(vcpu);
1838 		return RESUME_HOST;
1839 	}
1840 	switch (vcpu->arch.trap) {
1841 	/* We're good on these - the host merely wanted to get our attention */
1842 	case BOOK3S_INTERRUPT_HV_DECREMENTER:
1843 		vcpu->stat.dec_exits++;
1844 		r = RESUME_GUEST;
1845 		break;
1846 	case BOOK3S_INTERRUPT_EXTERNAL:
1847 		vcpu->stat.ext_intr_exits++;
1848 		r = RESUME_HOST;
1849 		break;
1850 	case BOOK3S_INTERRUPT_H_DOORBELL:
1851 	case BOOK3S_INTERRUPT_H_VIRT:
1852 		vcpu->stat.ext_intr_exits++;
1853 		r = RESUME_GUEST;
1854 		break;
1855 	/* These need to go to the nested HV */
1856 	case BOOK3S_INTERRUPT_NESTED_HV_DECREMENTER:
1857 		vcpu->arch.trap = BOOK3S_INTERRUPT_HV_DECREMENTER;
1858 		vcpu->stat.dec_exits++;
1859 		r = RESUME_HOST;
1860 		break;
1861 	/* SR/HMI/PMI are HV interrupts that host has handled. Resume guest.*/
1862 	case BOOK3S_INTERRUPT_HMI:
1863 	case BOOK3S_INTERRUPT_PERFMON:
1864 	case BOOK3S_INTERRUPT_SYSTEM_RESET:
1865 		r = RESUME_GUEST;
1866 		break;
1867 	case BOOK3S_INTERRUPT_MACHINE_CHECK:
1868 	{
1869 		static DEFINE_RATELIMIT_STATE(rs, DEFAULT_RATELIMIT_INTERVAL,
1870 					      DEFAULT_RATELIMIT_BURST);
1871 		/* Pass the machine check to the L1 guest */
1872 		r = RESUME_HOST;
1873 		/* Print the MCE event to host console. */
1874 		if (__ratelimit(&rs))
1875 			machine_check_print_event_info(&vcpu->arch.mce_evt, false, true);
1876 		break;
1877 	}
1878 	/*
1879 	 * We get these next two if the guest accesses a page which it thinks
1880 	 * it has mapped but which is not actually present, either because
1881 	 * it is for an emulated I/O device or because the corresonding
1882 	 * host page has been paged out.
1883 	 */
1884 	case BOOK3S_INTERRUPT_H_DATA_STORAGE:
1885 		srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
1886 		r = kvmhv_nested_page_fault(vcpu);
1887 		srcu_read_unlock(&vcpu->kvm->srcu, srcu_idx);
1888 		break;
1889 	case BOOK3S_INTERRUPT_H_INST_STORAGE:
1890 		vcpu->arch.fault_dar = kvmppc_get_pc(vcpu);
1891 		vcpu->arch.fault_dsisr = kvmppc_get_msr(vcpu) &
1892 					 DSISR_SRR1_MATCH_64S;
1893 		if (vcpu->arch.shregs.msr & HSRR1_HISI_WRITE)
1894 			vcpu->arch.fault_dsisr |= DSISR_ISSTORE;
1895 		srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
1896 		r = kvmhv_nested_page_fault(vcpu);
1897 		srcu_read_unlock(&vcpu->kvm->srcu, srcu_idx);
1898 		break;
1899 
1900 #ifdef CONFIG_PPC_TRANSACTIONAL_MEM
1901 	case BOOK3S_INTERRUPT_HV_SOFTPATCH:
1902 		/*
1903 		 * This occurs for various TM-related instructions that
1904 		 * we need to emulate on POWER9 DD2.2.  We have already
1905 		 * handled the cases where the guest was in real-suspend
1906 		 * mode and was transitioning to transactional state.
1907 		 */
1908 		r = kvmhv_p9_tm_emulation(vcpu);
1909 		if (r != -1)
1910 			break;
1911 		fallthrough; /* go to facility unavailable handler */
1912 #endif
1913 
1914 	case BOOK3S_INTERRUPT_H_FAC_UNAVAIL: {
1915 		u64 cause = vcpu->arch.hfscr >> 56;
1916 
1917 		/*
1918 		 * Only pass HFU interrupts to the L1 if the facility is
1919 		 * permitted but disabled by the L1's HFSCR, otherwise
1920 		 * the interrupt does not make sense to the L1 so turn
1921 		 * it into a HEAI.
1922 		 */
1923 		if (!(vcpu->arch.hfscr_permitted & (1UL << cause)) ||
1924 				(vcpu->arch.nested_hfscr & (1UL << cause))) {
1925 			vcpu->arch.trap = BOOK3S_INTERRUPT_H_EMUL_ASSIST;
1926 
1927 			/*
1928 			 * If the fetch failed, return to guest and
1929 			 * try executing it again.
1930 			 */
1931 			r = kvmppc_get_last_inst(vcpu, INST_GENERIC,
1932 						 &vcpu->arch.emul_inst);
1933 			if (r != EMULATE_DONE)
1934 				r = RESUME_GUEST;
1935 			else
1936 				r = RESUME_HOST;
1937 		} else {
1938 			r = RESUME_HOST;
1939 		}
1940 
1941 		break;
1942 	}
1943 
1944 	case BOOK3S_INTERRUPT_HV_RM_HARD:
1945 		vcpu->arch.trap = 0;
1946 		r = RESUME_GUEST;
1947 		if (!xics_on_xive())
1948 			kvmppc_xics_rm_complete(vcpu, 0);
1949 		break;
1950 	case BOOK3S_INTERRUPT_SYSCALL:
1951 	{
1952 		unsigned long req = kvmppc_get_gpr(vcpu, 3);
1953 
1954 		/*
1955 		 * The H_RPT_INVALIDATE hcalls issued by nested
1956 		 * guests for process-scoped invalidations when
1957 		 * GTSE=0, are handled here in L0.
1958 		 */
1959 		if (req == H_RPT_INVALIDATE) {
1960 			r = kvmppc_nested_h_rpt_invalidate(vcpu);
1961 			break;
1962 		}
1963 
1964 		r = RESUME_HOST;
1965 		break;
1966 	}
1967 	default:
1968 		r = RESUME_HOST;
1969 		break;
1970 	}
1971 
1972 	return r;
1973 }
1974 
1975 static int kvm_arch_vcpu_ioctl_get_sregs_hv(struct kvm_vcpu *vcpu,
1976 					    struct kvm_sregs *sregs)
1977 {
1978 	int i;
1979 
1980 	memset(sregs, 0, sizeof(struct kvm_sregs));
1981 	sregs->pvr = vcpu->arch.pvr;
1982 	for (i = 0; i < vcpu->arch.slb_max; i++) {
1983 		sregs->u.s.ppc64.slb[i].slbe = vcpu->arch.slb[i].orige;
1984 		sregs->u.s.ppc64.slb[i].slbv = vcpu->arch.slb[i].origv;
1985 	}
1986 
1987 	return 0;
1988 }
1989 
1990 static int kvm_arch_vcpu_ioctl_set_sregs_hv(struct kvm_vcpu *vcpu,
1991 					    struct kvm_sregs *sregs)
1992 {
1993 	int i, j;
1994 
1995 	/* Only accept the same PVR as the host's, since we can't spoof it */
1996 	if (sregs->pvr != vcpu->arch.pvr)
1997 		return -EINVAL;
1998 
1999 	j = 0;
2000 	for (i = 0; i < vcpu->arch.slb_nr; i++) {
2001 		if (sregs->u.s.ppc64.slb[i].slbe & SLB_ESID_V) {
2002 			vcpu->arch.slb[j].orige = sregs->u.s.ppc64.slb[i].slbe;
2003 			vcpu->arch.slb[j].origv = sregs->u.s.ppc64.slb[i].slbv;
2004 			++j;
2005 		}
2006 	}
2007 	vcpu->arch.slb_max = j;
2008 
2009 	return 0;
2010 }
2011 
2012 /*
2013  * Enforce limits on guest LPCR values based on hardware availability,
2014  * guest configuration, and possibly hypervisor support and security
2015  * concerns.
2016  */
2017 unsigned long kvmppc_filter_lpcr_hv(struct kvm *kvm, unsigned long lpcr)
2018 {
2019 	/* LPCR_TC only applies to HPT guests */
2020 	if (kvm_is_radix(kvm))
2021 		lpcr &= ~LPCR_TC;
2022 
2023 	/* On POWER8 and above, userspace can modify AIL */
2024 	if (!cpu_has_feature(CPU_FTR_ARCH_207S))
2025 		lpcr &= ~LPCR_AIL;
2026 	if ((lpcr & LPCR_AIL) != LPCR_AIL_3)
2027 		lpcr &= ~LPCR_AIL; /* LPCR[AIL]=1/2 is disallowed */
2028 	/*
2029 	 * On some POWER9s we force AIL off for radix guests to prevent
2030 	 * executing in MSR[HV]=1 mode with the MMU enabled and PIDR set to
2031 	 * guest, which can result in Q0 translations with LPID=0 PID=PIDR to
2032 	 * be cached, which the host TLB management does not expect.
2033 	 */
2034 	if (kvm_is_radix(kvm) && cpu_has_feature(CPU_FTR_P9_RADIX_PREFETCH_BUG))
2035 		lpcr &= ~LPCR_AIL;
2036 
2037 	/*
2038 	 * On POWER9, allow userspace to enable large decrementer for the
2039 	 * guest, whether or not the host has it enabled.
2040 	 */
2041 	if (!cpu_has_feature(CPU_FTR_ARCH_300))
2042 		lpcr &= ~LPCR_LD;
2043 
2044 	return lpcr;
2045 }
2046 
2047 static void verify_lpcr(struct kvm *kvm, unsigned long lpcr)
2048 {
2049 	if (lpcr != kvmppc_filter_lpcr_hv(kvm, lpcr)) {
2050 		WARN_ONCE(1, "lpcr 0x%lx differs from filtered 0x%lx\n",
2051 			  lpcr, kvmppc_filter_lpcr_hv(kvm, lpcr));
2052 	}
2053 }
2054 
2055 static void kvmppc_set_lpcr(struct kvm_vcpu *vcpu, u64 new_lpcr,
2056 		bool preserve_top32)
2057 {
2058 	struct kvm *kvm = vcpu->kvm;
2059 	struct kvmppc_vcore *vc = vcpu->arch.vcore;
2060 	u64 mask;
2061 
2062 	spin_lock(&vc->lock);
2063 
2064 	/*
2065 	 * Userspace can only modify
2066 	 * DPFD (default prefetch depth), ILE (interrupt little-endian),
2067 	 * TC (translation control), AIL (alternate interrupt location),
2068 	 * LD (large decrementer).
2069 	 * These are subject to restrictions from kvmppc_filter_lcpr_hv().
2070 	 */
2071 	mask = LPCR_DPFD | LPCR_ILE | LPCR_TC | LPCR_AIL | LPCR_LD;
2072 
2073 	/* Broken 32-bit version of LPCR must not clear top bits */
2074 	if (preserve_top32)
2075 		mask &= 0xFFFFFFFF;
2076 
2077 	new_lpcr = kvmppc_filter_lpcr_hv(kvm,
2078 			(vc->lpcr & ~mask) | (new_lpcr & mask));
2079 
2080 	/*
2081 	 * If ILE (interrupt little-endian) has changed, update the
2082 	 * MSR_LE bit in the intr_msr for each vcpu in this vcore.
2083 	 */
2084 	if ((new_lpcr & LPCR_ILE) != (vc->lpcr & LPCR_ILE)) {
2085 		struct kvm_vcpu *vcpu;
2086 		unsigned long i;
2087 
2088 		kvm_for_each_vcpu(i, vcpu, kvm) {
2089 			if (vcpu->arch.vcore != vc)
2090 				continue;
2091 			if (new_lpcr & LPCR_ILE)
2092 				vcpu->arch.intr_msr |= MSR_LE;
2093 			else
2094 				vcpu->arch.intr_msr &= ~MSR_LE;
2095 		}
2096 	}
2097 
2098 	vc->lpcr = new_lpcr;
2099 
2100 	spin_unlock(&vc->lock);
2101 }
2102 
2103 static int kvmppc_get_one_reg_hv(struct kvm_vcpu *vcpu, u64 id,
2104 				 union kvmppc_one_reg *val)
2105 {
2106 	int r = 0;
2107 	long int i;
2108 
2109 	switch (id) {
2110 	case KVM_REG_PPC_DEBUG_INST:
2111 		*val = get_reg_val(id, KVMPPC_INST_SW_BREAKPOINT);
2112 		break;
2113 	case KVM_REG_PPC_HIOR:
2114 		*val = get_reg_val(id, 0);
2115 		break;
2116 	case KVM_REG_PPC_DABR:
2117 		*val = get_reg_val(id, vcpu->arch.dabr);
2118 		break;
2119 	case KVM_REG_PPC_DABRX:
2120 		*val = get_reg_val(id, vcpu->arch.dabrx);
2121 		break;
2122 	case KVM_REG_PPC_DSCR:
2123 		*val = get_reg_val(id, vcpu->arch.dscr);
2124 		break;
2125 	case KVM_REG_PPC_PURR:
2126 		*val = get_reg_val(id, vcpu->arch.purr);
2127 		break;
2128 	case KVM_REG_PPC_SPURR:
2129 		*val = get_reg_val(id, vcpu->arch.spurr);
2130 		break;
2131 	case KVM_REG_PPC_AMR:
2132 		*val = get_reg_val(id, vcpu->arch.amr);
2133 		break;
2134 	case KVM_REG_PPC_UAMOR:
2135 		*val = get_reg_val(id, vcpu->arch.uamor);
2136 		break;
2137 	case KVM_REG_PPC_MMCR0 ... KVM_REG_PPC_MMCR1:
2138 		i = id - KVM_REG_PPC_MMCR0;
2139 		*val = get_reg_val(id, vcpu->arch.mmcr[i]);
2140 		break;
2141 	case KVM_REG_PPC_MMCR2:
2142 		*val = get_reg_val(id, vcpu->arch.mmcr[2]);
2143 		break;
2144 	case KVM_REG_PPC_MMCRA:
2145 		*val = get_reg_val(id, vcpu->arch.mmcra);
2146 		break;
2147 	case KVM_REG_PPC_MMCRS:
2148 		*val = get_reg_val(id, vcpu->arch.mmcrs);
2149 		break;
2150 	case KVM_REG_PPC_MMCR3:
2151 		*val = get_reg_val(id, vcpu->arch.mmcr[3]);
2152 		break;
2153 	case KVM_REG_PPC_PMC1 ... KVM_REG_PPC_PMC8:
2154 		i = id - KVM_REG_PPC_PMC1;
2155 		*val = get_reg_val(id, vcpu->arch.pmc[i]);
2156 		break;
2157 	case KVM_REG_PPC_SPMC1 ... KVM_REG_PPC_SPMC2:
2158 		i = id - KVM_REG_PPC_SPMC1;
2159 		*val = get_reg_val(id, vcpu->arch.spmc[i]);
2160 		break;
2161 	case KVM_REG_PPC_SIAR:
2162 		*val = get_reg_val(id, vcpu->arch.siar);
2163 		break;
2164 	case KVM_REG_PPC_SDAR:
2165 		*val = get_reg_val(id, vcpu->arch.sdar);
2166 		break;
2167 	case KVM_REG_PPC_SIER:
2168 		*val = get_reg_val(id, vcpu->arch.sier[0]);
2169 		break;
2170 	case KVM_REG_PPC_SIER2:
2171 		*val = get_reg_val(id, vcpu->arch.sier[1]);
2172 		break;
2173 	case KVM_REG_PPC_SIER3:
2174 		*val = get_reg_val(id, vcpu->arch.sier[2]);
2175 		break;
2176 	case KVM_REG_PPC_IAMR:
2177 		*val = get_reg_val(id, vcpu->arch.iamr);
2178 		break;
2179 	case KVM_REG_PPC_PSPB:
2180 		*val = get_reg_val(id, vcpu->arch.pspb);
2181 		break;
2182 	case KVM_REG_PPC_DPDES:
2183 		/*
2184 		 * On POWER9, where we are emulating msgsndp etc.,
2185 		 * we return 1 bit for each vcpu, which can come from
2186 		 * either vcore->dpdes or doorbell_request.
2187 		 * On POWER8, doorbell_request is 0.
2188 		 */
2189 		if (cpu_has_feature(CPU_FTR_ARCH_300))
2190 			*val = get_reg_val(id, vcpu->arch.doorbell_request);
2191 		else
2192 			*val = get_reg_val(id, vcpu->arch.vcore->dpdes);
2193 		break;
2194 	case KVM_REG_PPC_VTB:
2195 		*val = get_reg_val(id, vcpu->arch.vcore->vtb);
2196 		break;
2197 	case KVM_REG_PPC_DAWR:
2198 		*val = get_reg_val(id, vcpu->arch.dawr0);
2199 		break;
2200 	case KVM_REG_PPC_DAWRX:
2201 		*val = get_reg_val(id, vcpu->arch.dawrx0);
2202 		break;
2203 	case KVM_REG_PPC_DAWR1:
2204 		*val = get_reg_val(id, vcpu->arch.dawr1);
2205 		break;
2206 	case KVM_REG_PPC_DAWRX1:
2207 		*val = get_reg_val(id, vcpu->arch.dawrx1);
2208 		break;
2209 	case KVM_REG_PPC_CIABR:
2210 		*val = get_reg_val(id, vcpu->arch.ciabr);
2211 		break;
2212 	case KVM_REG_PPC_CSIGR:
2213 		*val = get_reg_val(id, vcpu->arch.csigr);
2214 		break;
2215 	case KVM_REG_PPC_TACR:
2216 		*val = get_reg_val(id, vcpu->arch.tacr);
2217 		break;
2218 	case KVM_REG_PPC_TCSCR:
2219 		*val = get_reg_val(id, vcpu->arch.tcscr);
2220 		break;
2221 	case KVM_REG_PPC_PID:
2222 		*val = get_reg_val(id, vcpu->arch.pid);
2223 		break;
2224 	case KVM_REG_PPC_ACOP:
2225 		*val = get_reg_val(id, vcpu->arch.acop);
2226 		break;
2227 	case KVM_REG_PPC_WORT:
2228 		*val = get_reg_val(id, vcpu->arch.wort);
2229 		break;
2230 	case KVM_REG_PPC_TIDR:
2231 		*val = get_reg_val(id, vcpu->arch.tid);
2232 		break;
2233 	case KVM_REG_PPC_PSSCR:
2234 		*val = get_reg_val(id, vcpu->arch.psscr);
2235 		break;
2236 	case KVM_REG_PPC_VPA_ADDR:
2237 		spin_lock(&vcpu->arch.vpa_update_lock);
2238 		*val = get_reg_val(id, vcpu->arch.vpa.next_gpa);
2239 		spin_unlock(&vcpu->arch.vpa_update_lock);
2240 		break;
2241 	case KVM_REG_PPC_VPA_SLB:
2242 		spin_lock(&vcpu->arch.vpa_update_lock);
2243 		val->vpaval.addr = vcpu->arch.slb_shadow.next_gpa;
2244 		val->vpaval.length = vcpu->arch.slb_shadow.len;
2245 		spin_unlock(&vcpu->arch.vpa_update_lock);
2246 		break;
2247 	case KVM_REG_PPC_VPA_DTL:
2248 		spin_lock(&vcpu->arch.vpa_update_lock);
2249 		val->vpaval.addr = vcpu->arch.dtl.next_gpa;
2250 		val->vpaval.length = vcpu->arch.dtl.len;
2251 		spin_unlock(&vcpu->arch.vpa_update_lock);
2252 		break;
2253 	case KVM_REG_PPC_TB_OFFSET:
2254 		*val = get_reg_val(id, vcpu->arch.vcore->tb_offset);
2255 		break;
2256 	case KVM_REG_PPC_LPCR:
2257 	case KVM_REG_PPC_LPCR_64:
2258 		*val = get_reg_val(id, vcpu->arch.vcore->lpcr);
2259 		break;
2260 	case KVM_REG_PPC_PPR:
2261 		*val = get_reg_val(id, vcpu->arch.ppr);
2262 		break;
2263 #ifdef CONFIG_PPC_TRANSACTIONAL_MEM
2264 	case KVM_REG_PPC_TFHAR:
2265 		*val = get_reg_val(id, vcpu->arch.tfhar);
2266 		break;
2267 	case KVM_REG_PPC_TFIAR:
2268 		*val = get_reg_val(id, vcpu->arch.tfiar);
2269 		break;
2270 	case KVM_REG_PPC_TEXASR:
2271 		*val = get_reg_val(id, vcpu->arch.texasr);
2272 		break;
2273 	case KVM_REG_PPC_TM_GPR0 ... KVM_REG_PPC_TM_GPR31:
2274 		i = id - KVM_REG_PPC_TM_GPR0;
2275 		*val = get_reg_val(id, vcpu->arch.gpr_tm[i]);
2276 		break;
2277 	case KVM_REG_PPC_TM_VSR0 ... KVM_REG_PPC_TM_VSR63:
2278 	{
2279 		int j;
2280 		i = id - KVM_REG_PPC_TM_VSR0;
2281 		if (i < 32)
2282 			for (j = 0; j < TS_FPRWIDTH; j++)
2283 				val->vsxval[j] = vcpu->arch.fp_tm.fpr[i][j];
2284 		else {
2285 			if (cpu_has_feature(CPU_FTR_ALTIVEC))
2286 				val->vval = vcpu->arch.vr_tm.vr[i-32];
2287 			else
2288 				r = -ENXIO;
2289 		}
2290 		break;
2291 	}
2292 	case KVM_REG_PPC_TM_CR:
2293 		*val = get_reg_val(id, vcpu->arch.cr_tm);
2294 		break;
2295 	case KVM_REG_PPC_TM_XER:
2296 		*val = get_reg_val(id, vcpu->arch.xer_tm);
2297 		break;
2298 	case KVM_REG_PPC_TM_LR:
2299 		*val = get_reg_val(id, vcpu->arch.lr_tm);
2300 		break;
2301 	case KVM_REG_PPC_TM_CTR:
2302 		*val = get_reg_val(id, vcpu->arch.ctr_tm);
2303 		break;
2304 	case KVM_REG_PPC_TM_FPSCR:
2305 		*val = get_reg_val(id, vcpu->arch.fp_tm.fpscr);
2306 		break;
2307 	case KVM_REG_PPC_TM_AMR:
2308 		*val = get_reg_val(id, vcpu->arch.amr_tm);
2309 		break;
2310 	case KVM_REG_PPC_TM_PPR:
2311 		*val = get_reg_val(id, vcpu->arch.ppr_tm);
2312 		break;
2313 	case KVM_REG_PPC_TM_VRSAVE:
2314 		*val = get_reg_val(id, vcpu->arch.vrsave_tm);
2315 		break;
2316 	case KVM_REG_PPC_TM_VSCR:
2317 		if (cpu_has_feature(CPU_FTR_ALTIVEC))
2318 			*val = get_reg_val(id, vcpu->arch.vr_tm.vscr.u[3]);
2319 		else
2320 			r = -ENXIO;
2321 		break;
2322 	case KVM_REG_PPC_TM_DSCR:
2323 		*val = get_reg_val(id, vcpu->arch.dscr_tm);
2324 		break;
2325 	case KVM_REG_PPC_TM_TAR:
2326 		*val = get_reg_val(id, vcpu->arch.tar_tm);
2327 		break;
2328 #endif
2329 	case KVM_REG_PPC_ARCH_COMPAT:
2330 		*val = get_reg_val(id, vcpu->arch.vcore->arch_compat);
2331 		break;
2332 	case KVM_REG_PPC_DEC_EXPIRY:
2333 		*val = get_reg_val(id, vcpu->arch.dec_expires);
2334 		break;
2335 	case KVM_REG_PPC_ONLINE:
2336 		*val = get_reg_val(id, vcpu->arch.online);
2337 		break;
2338 	case KVM_REG_PPC_PTCR:
2339 		*val = get_reg_val(id, vcpu->kvm->arch.l1_ptcr);
2340 		break;
2341 	default:
2342 		r = -EINVAL;
2343 		break;
2344 	}
2345 
2346 	return r;
2347 }
2348 
2349 static int kvmppc_set_one_reg_hv(struct kvm_vcpu *vcpu, u64 id,
2350 				 union kvmppc_one_reg *val)
2351 {
2352 	int r = 0;
2353 	long int i;
2354 	unsigned long addr, len;
2355 
2356 	switch (id) {
2357 	case KVM_REG_PPC_HIOR:
2358 		/* Only allow this to be set to zero */
2359 		if (set_reg_val(id, *val))
2360 			r = -EINVAL;
2361 		break;
2362 	case KVM_REG_PPC_DABR:
2363 		vcpu->arch.dabr = set_reg_val(id, *val);
2364 		break;
2365 	case KVM_REG_PPC_DABRX:
2366 		vcpu->arch.dabrx = set_reg_val(id, *val) & ~DABRX_HYP;
2367 		break;
2368 	case KVM_REG_PPC_DSCR:
2369 		vcpu->arch.dscr = set_reg_val(id, *val);
2370 		break;
2371 	case KVM_REG_PPC_PURR:
2372 		vcpu->arch.purr = set_reg_val(id, *val);
2373 		break;
2374 	case KVM_REG_PPC_SPURR:
2375 		vcpu->arch.spurr = set_reg_val(id, *val);
2376 		break;
2377 	case KVM_REG_PPC_AMR:
2378 		vcpu->arch.amr = set_reg_val(id, *val);
2379 		break;
2380 	case KVM_REG_PPC_UAMOR:
2381 		vcpu->arch.uamor = set_reg_val(id, *val);
2382 		break;
2383 	case KVM_REG_PPC_MMCR0 ... KVM_REG_PPC_MMCR1:
2384 		i = id - KVM_REG_PPC_MMCR0;
2385 		vcpu->arch.mmcr[i] = set_reg_val(id, *val);
2386 		break;
2387 	case KVM_REG_PPC_MMCR2:
2388 		vcpu->arch.mmcr[2] = set_reg_val(id, *val);
2389 		break;
2390 	case KVM_REG_PPC_MMCRA:
2391 		vcpu->arch.mmcra = set_reg_val(id, *val);
2392 		break;
2393 	case KVM_REG_PPC_MMCRS:
2394 		vcpu->arch.mmcrs = set_reg_val(id, *val);
2395 		break;
2396 	case KVM_REG_PPC_MMCR3:
2397 		*val = get_reg_val(id, vcpu->arch.mmcr[3]);
2398 		break;
2399 	case KVM_REG_PPC_PMC1 ... KVM_REG_PPC_PMC8:
2400 		i = id - KVM_REG_PPC_PMC1;
2401 		vcpu->arch.pmc[i] = set_reg_val(id, *val);
2402 		break;
2403 	case KVM_REG_PPC_SPMC1 ... KVM_REG_PPC_SPMC2:
2404 		i = id - KVM_REG_PPC_SPMC1;
2405 		vcpu->arch.spmc[i] = set_reg_val(id, *val);
2406 		break;
2407 	case KVM_REG_PPC_SIAR:
2408 		vcpu->arch.siar = set_reg_val(id, *val);
2409 		break;
2410 	case KVM_REG_PPC_SDAR:
2411 		vcpu->arch.sdar = set_reg_val(id, *val);
2412 		break;
2413 	case KVM_REG_PPC_SIER:
2414 		vcpu->arch.sier[0] = set_reg_val(id, *val);
2415 		break;
2416 	case KVM_REG_PPC_SIER2:
2417 		vcpu->arch.sier[1] = set_reg_val(id, *val);
2418 		break;
2419 	case KVM_REG_PPC_SIER3:
2420 		vcpu->arch.sier[2] = set_reg_val(id, *val);
2421 		break;
2422 	case KVM_REG_PPC_IAMR:
2423 		vcpu->arch.iamr = set_reg_val(id, *val);
2424 		break;
2425 	case KVM_REG_PPC_PSPB:
2426 		vcpu->arch.pspb = set_reg_val(id, *val);
2427 		break;
2428 	case KVM_REG_PPC_DPDES:
2429 		if (cpu_has_feature(CPU_FTR_ARCH_300))
2430 			vcpu->arch.doorbell_request = set_reg_val(id, *val) & 1;
2431 		else
2432 			vcpu->arch.vcore->dpdes = set_reg_val(id, *val);
2433 		break;
2434 	case KVM_REG_PPC_VTB:
2435 		vcpu->arch.vcore->vtb = set_reg_val(id, *val);
2436 		break;
2437 	case KVM_REG_PPC_DAWR:
2438 		vcpu->arch.dawr0 = set_reg_val(id, *val);
2439 		break;
2440 	case KVM_REG_PPC_DAWRX:
2441 		vcpu->arch.dawrx0 = set_reg_val(id, *val) & ~DAWRX_HYP;
2442 		break;
2443 	case KVM_REG_PPC_DAWR1:
2444 		vcpu->arch.dawr1 = set_reg_val(id, *val);
2445 		break;
2446 	case KVM_REG_PPC_DAWRX1:
2447 		vcpu->arch.dawrx1 = set_reg_val(id, *val) & ~DAWRX_HYP;
2448 		break;
2449 	case KVM_REG_PPC_CIABR:
2450 		vcpu->arch.ciabr = set_reg_val(id, *val);
2451 		/* Don't allow setting breakpoints in hypervisor code */
2452 		if ((vcpu->arch.ciabr & CIABR_PRIV) == CIABR_PRIV_HYPER)
2453 			vcpu->arch.ciabr &= ~CIABR_PRIV;	/* disable */
2454 		break;
2455 	case KVM_REG_PPC_CSIGR:
2456 		vcpu->arch.csigr = set_reg_val(id, *val);
2457 		break;
2458 	case KVM_REG_PPC_TACR:
2459 		vcpu->arch.tacr = set_reg_val(id, *val);
2460 		break;
2461 	case KVM_REG_PPC_TCSCR:
2462 		vcpu->arch.tcscr = set_reg_val(id, *val);
2463 		break;
2464 	case KVM_REG_PPC_PID:
2465 		vcpu->arch.pid = set_reg_val(id, *val);
2466 		break;
2467 	case KVM_REG_PPC_ACOP:
2468 		vcpu->arch.acop = set_reg_val(id, *val);
2469 		break;
2470 	case KVM_REG_PPC_WORT:
2471 		vcpu->arch.wort = set_reg_val(id, *val);
2472 		break;
2473 	case KVM_REG_PPC_TIDR:
2474 		vcpu->arch.tid = set_reg_val(id, *val);
2475 		break;
2476 	case KVM_REG_PPC_PSSCR:
2477 		vcpu->arch.psscr = set_reg_val(id, *val) & PSSCR_GUEST_VIS;
2478 		break;
2479 	case KVM_REG_PPC_VPA_ADDR:
2480 		addr = set_reg_val(id, *val);
2481 		r = -EINVAL;
2482 		if (!addr && (vcpu->arch.slb_shadow.next_gpa ||
2483 			      vcpu->arch.dtl.next_gpa))
2484 			break;
2485 		r = set_vpa(vcpu, &vcpu->arch.vpa, addr, sizeof(struct lppaca));
2486 		break;
2487 	case KVM_REG_PPC_VPA_SLB:
2488 		addr = val->vpaval.addr;
2489 		len = val->vpaval.length;
2490 		r = -EINVAL;
2491 		if (addr && !vcpu->arch.vpa.next_gpa)
2492 			break;
2493 		r = set_vpa(vcpu, &vcpu->arch.slb_shadow, addr, len);
2494 		break;
2495 	case KVM_REG_PPC_VPA_DTL:
2496 		addr = val->vpaval.addr;
2497 		len = val->vpaval.length;
2498 		r = -EINVAL;
2499 		if (addr && (len < sizeof(struct dtl_entry) ||
2500 			     !vcpu->arch.vpa.next_gpa))
2501 			break;
2502 		len -= len % sizeof(struct dtl_entry);
2503 		r = set_vpa(vcpu, &vcpu->arch.dtl, addr, len);
2504 		break;
2505 	case KVM_REG_PPC_TB_OFFSET:
2506 		/* round up to multiple of 2^24 */
2507 		vcpu->arch.vcore->tb_offset =
2508 			ALIGN(set_reg_val(id, *val), 1UL << 24);
2509 		break;
2510 	case KVM_REG_PPC_LPCR:
2511 		kvmppc_set_lpcr(vcpu, set_reg_val(id, *val), true);
2512 		break;
2513 	case KVM_REG_PPC_LPCR_64:
2514 		kvmppc_set_lpcr(vcpu, set_reg_val(id, *val), false);
2515 		break;
2516 	case KVM_REG_PPC_PPR:
2517 		vcpu->arch.ppr = set_reg_val(id, *val);
2518 		break;
2519 #ifdef CONFIG_PPC_TRANSACTIONAL_MEM
2520 	case KVM_REG_PPC_TFHAR:
2521 		vcpu->arch.tfhar = set_reg_val(id, *val);
2522 		break;
2523 	case KVM_REG_PPC_TFIAR:
2524 		vcpu->arch.tfiar = set_reg_val(id, *val);
2525 		break;
2526 	case KVM_REG_PPC_TEXASR:
2527 		vcpu->arch.texasr = set_reg_val(id, *val);
2528 		break;
2529 	case KVM_REG_PPC_TM_GPR0 ... KVM_REG_PPC_TM_GPR31:
2530 		i = id - KVM_REG_PPC_TM_GPR0;
2531 		vcpu->arch.gpr_tm[i] = set_reg_val(id, *val);
2532 		break;
2533 	case KVM_REG_PPC_TM_VSR0 ... KVM_REG_PPC_TM_VSR63:
2534 	{
2535 		int j;
2536 		i = id - KVM_REG_PPC_TM_VSR0;
2537 		if (i < 32)
2538 			for (j = 0; j < TS_FPRWIDTH; j++)
2539 				vcpu->arch.fp_tm.fpr[i][j] = val->vsxval[j];
2540 		else
2541 			if (cpu_has_feature(CPU_FTR_ALTIVEC))
2542 				vcpu->arch.vr_tm.vr[i-32] = val->vval;
2543 			else
2544 				r = -ENXIO;
2545 		break;
2546 	}
2547 	case KVM_REG_PPC_TM_CR:
2548 		vcpu->arch.cr_tm = set_reg_val(id, *val);
2549 		break;
2550 	case KVM_REG_PPC_TM_XER:
2551 		vcpu->arch.xer_tm = set_reg_val(id, *val);
2552 		break;
2553 	case KVM_REG_PPC_TM_LR:
2554 		vcpu->arch.lr_tm = set_reg_val(id, *val);
2555 		break;
2556 	case KVM_REG_PPC_TM_CTR:
2557 		vcpu->arch.ctr_tm = set_reg_val(id, *val);
2558 		break;
2559 	case KVM_REG_PPC_TM_FPSCR:
2560 		vcpu->arch.fp_tm.fpscr = set_reg_val(id, *val);
2561 		break;
2562 	case KVM_REG_PPC_TM_AMR:
2563 		vcpu->arch.amr_tm = set_reg_val(id, *val);
2564 		break;
2565 	case KVM_REG_PPC_TM_PPR:
2566 		vcpu->arch.ppr_tm = set_reg_val(id, *val);
2567 		break;
2568 	case KVM_REG_PPC_TM_VRSAVE:
2569 		vcpu->arch.vrsave_tm = set_reg_val(id, *val);
2570 		break;
2571 	case KVM_REG_PPC_TM_VSCR:
2572 		if (cpu_has_feature(CPU_FTR_ALTIVEC))
2573 			vcpu->arch.vr.vscr.u[3] = set_reg_val(id, *val);
2574 		else
2575 			r = - ENXIO;
2576 		break;
2577 	case KVM_REG_PPC_TM_DSCR:
2578 		vcpu->arch.dscr_tm = set_reg_val(id, *val);
2579 		break;
2580 	case KVM_REG_PPC_TM_TAR:
2581 		vcpu->arch.tar_tm = set_reg_val(id, *val);
2582 		break;
2583 #endif
2584 	case KVM_REG_PPC_ARCH_COMPAT:
2585 		r = kvmppc_set_arch_compat(vcpu, set_reg_val(id, *val));
2586 		break;
2587 	case KVM_REG_PPC_DEC_EXPIRY:
2588 		vcpu->arch.dec_expires = set_reg_val(id, *val);
2589 		break;
2590 	case KVM_REG_PPC_ONLINE:
2591 		i = set_reg_val(id, *val);
2592 		if (i && !vcpu->arch.online)
2593 			atomic_inc(&vcpu->arch.vcore->online_count);
2594 		else if (!i && vcpu->arch.online)
2595 			atomic_dec(&vcpu->arch.vcore->online_count);
2596 		vcpu->arch.online = i;
2597 		break;
2598 	case KVM_REG_PPC_PTCR:
2599 		vcpu->kvm->arch.l1_ptcr = set_reg_val(id, *val);
2600 		break;
2601 	default:
2602 		r = -EINVAL;
2603 		break;
2604 	}
2605 
2606 	return r;
2607 }
2608 
2609 /*
2610  * On POWER9, threads are independent and can be in different partitions.
2611  * Therefore we consider each thread to be a subcore.
2612  * There is a restriction that all threads have to be in the same
2613  * MMU mode (radix or HPT), unfortunately, but since we only support
2614  * HPT guests on a HPT host so far, that isn't an impediment yet.
2615  */
2616 static int threads_per_vcore(struct kvm *kvm)
2617 {
2618 	if (cpu_has_feature(CPU_FTR_ARCH_300))
2619 		return 1;
2620 	return threads_per_subcore;
2621 }
2622 
2623 static struct kvmppc_vcore *kvmppc_vcore_create(struct kvm *kvm, int id)
2624 {
2625 	struct kvmppc_vcore *vcore;
2626 
2627 	vcore = kzalloc(sizeof(struct kvmppc_vcore), GFP_KERNEL);
2628 
2629 	if (vcore == NULL)
2630 		return NULL;
2631 
2632 	spin_lock_init(&vcore->lock);
2633 	spin_lock_init(&vcore->stoltb_lock);
2634 	rcuwait_init(&vcore->wait);
2635 	vcore->preempt_tb = TB_NIL;
2636 	vcore->lpcr = kvm->arch.lpcr;
2637 	vcore->first_vcpuid = id;
2638 	vcore->kvm = kvm;
2639 	INIT_LIST_HEAD(&vcore->preempt_list);
2640 
2641 	return vcore;
2642 }
2643 
2644 #ifdef CONFIG_KVM_BOOK3S_HV_EXIT_TIMING
2645 static struct debugfs_timings_element {
2646 	const char *name;
2647 	size_t offset;
2648 } timings[] = {
2649 	{"rm_entry",	offsetof(struct kvm_vcpu, arch.rm_entry)},
2650 	{"rm_intr",	offsetof(struct kvm_vcpu, arch.rm_intr)},
2651 	{"rm_exit",	offsetof(struct kvm_vcpu, arch.rm_exit)},
2652 	{"guest",	offsetof(struct kvm_vcpu, arch.guest_time)},
2653 	{"cede",	offsetof(struct kvm_vcpu, arch.cede_time)},
2654 };
2655 
2656 #define N_TIMINGS	(ARRAY_SIZE(timings))
2657 
2658 struct debugfs_timings_state {
2659 	struct kvm_vcpu	*vcpu;
2660 	unsigned int	buflen;
2661 	char		buf[N_TIMINGS * 100];
2662 };
2663 
2664 static int debugfs_timings_open(struct inode *inode, struct file *file)
2665 {
2666 	struct kvm_vcpu *vcpu = inode->i_private;
2667 	struct debugfs_timings_state *p;
2668 
2669 	p = kzalloc(sizeof(*p), GFP_KERNEL);
2670 	if (!p)
2671 		return -ENOMEM;
2672 
2673 	kvm_get_kvm(vcpu->kvm);
2674 	p->vcpu = vcpu;
2675 	file->private_data = p;
2676 
2677 	return nonseekable_open(inode, file);
2678 }
2679 
2680 static int debugfs_timings_release(struct inode *inode, struct file *file)
2681 {
2682 	struct debugfs_timings_state *p = file->private_data;
2683 
2684 	kvm_put_kvm(p->vcpu->kvm);
2685 	kfree(p);
2686 	return 0;
2687 }
2688 
2689 static ssize_t debugfs_timings_read(struct file *file, char __user *buf,
2690 				    size_t len, loff_t *ppos)
2691 {
2692 	struct debugfs_timings_state *p = file->private_data;
2693 	struct kvm_vcpu *vcpu = p->vcpu;
2694 	char *s, *buf_end;
2695 	struct kvmhv_tb_accumulator tb;
2696 	u64 count;
2697 	loff_t pos;
2698 	ssize_t n;
2699 	int i, loops;
2700 	bool ok;
2701 
2702 	if (!p->buflen) {
2703 		s = p->buf;
2704 		buf_end = s + sizeof(p->buf);
2705 		for (i = 0; i < N_TIMINGS; ++i) {
2706 			struct kvmhv_tb_accumulator *acc;
2707 
2708 			acc = (struct kvmhv_tb_accumulator *)
2709 				((unsigned long)vcpu + timings[i].offset);
2710 			ok = false;
2711 			for (loops = 0; loops < 1000; ++loops) {
2712 				count = acc->seqcount;
2713 				if (!(count & 1)) {
2714 					smp_rmb();
2715 					tb = *acc;
2716 					smp_rmb();
2717 					if (count == acc->seqcount) {
2718 						ok = true;
2719 						break;
2720 					}
2721 				}
2722 				udelay(1);
2723 			}
2724 			if (!ok)
2725 				snprintf(s, buf_end - s, "%s: stuck\n",
2726 					timings[i].name);
2727 			else
2728 				snprintf(s, buf_end - s,
2729 					"%s: %llu %llu %llu %llu\n",
2730 					timings[i].name, count / 2,
2731 					tb_to_ns(tb.tb_total),
2732 					tb_to_ns(tb.tb_min),
2733 					tb_to_ns(tb.tb_max));
2734 			s += strlen(s);
2735 		}
2736 		p->buflen = s - p->buf;
2737 	}
2738 
2739 	pos = *ppos;
2740 	if (pos >= p->buflen)
2741 		return 0;
2742 	if (len > p->buflen - pos)
2743 		len = p->buflen - pos;
2744 	n = copy_to_user(buf, p->buf + pos, len);
2745 	if (n) {
2746 		if (n == len)
2747 			return -EFAULT;
2748 		len -= n;
2749 	}
2750 	*ppos = pos + len;
2751 	return len;
2752 }
2753 
2754 static ssize_t debugfs_timings_write(struct file *file, const char __user *buf,
2755 				     size_t len, loff_t *ppos)
2756 {
2757 	return -EACCES;
2758 }
2759 
2760 static const struct file_operations debugfs_timings_ops = {
2761 	.owner	 = THIS_MODULE,
2762 	.open	 = debugfs_timings_open,
2763 	.release = debugfs_timings_release,
2764 	.read	 = debugfs_timings_read,
2765 	.write	 = debugfs_timings_write,
2766 	.llseek	 = generic_file_llseek,
2767 };
2768 
2769 /* Create a debugfs directory for the vcpu */
2770 static int kvmppc_arch_create_vcpu_debugfs_hv(struct kvm_vcpu *vcpu, struct dentry *debugfs_dentry)
2771 {
2772 	debugfs_create_file("timings", 0444, debugfs_dentry, vcpu,
2773 			    &debugfs_timings_ops);
2774 	return 0;
2775 }
2776 
2777 #else /* CONFIG_KVM_BOOK3S_HV_EXIT_TIMING */
2778 static int kvmppc_arch_create_vcpu_debugfs_hv(struct kvm_vcpu *vcpu, struct dentry *debugfs_dentry)
2779 {
2780 	return 0;
2781 }
2782 #endif /* CONFIG_KVM_BOOK3S_HV_EXIT_TIMING */
2783 
2784 static int kvmppc_core_vcpu_create_hv(struct kvm_vcpu *vcpu)
2785 {
2786 	int err;
2787 	int core;
2788 	struct kvmppc_vcore *vcore;
2789 	struct kvm *kvm;
2790 	unsigned int id;
2791 
2792 	kvm = vcpu->kvm;
2793 	id = vcpu->vcpu_id;
2794 
2795 	vcpu->arch.shared = &vcpu->arch.shregs;
2796 #ifdef CONFIG_KVM_BOOK3S_PR_POSSIBLE
2797 	/*
2798 	 * The shared struct is never shared on HV,
2799 	 * so we can always use host endianness
2800 	 */
2801 #ifdef __BIG_ENDIAN__
2802 	vcpu->arch.shared_big_endian = true;
2803 #else
2804 	vcpu->arch.shared_big_endian = false;
2805 #endif
2806 #endif
2807 	vcpu->arch.mmcr[0] = MMCR0_FC;
2808 	if (cpu_has_feature(CPU_FTR_ARCH_31)) {
2809 		vcpu->arch.mmcr[0] |= MMCR0_PMCCEXT;
2810 		vcpu->arch.mmcra = MMCRA_BHRB_DISABLE;
2811 	}
2812 
2813 	vcpu->arch.ctrl = CTRL_RUNLATCH;
2814 	/* default to host PVR, since we can't spoof it */
2815 	kvmppc_set_pvr_hv(vcpu, mfspr(SPRN_PVR));
2816 	spin_lock_init(&vcpu->arch.vpa_update_lock);
2817 	spin_lock_init(&vcpu->arch.tbacct_lock);
2818 	vcpu->arch.busy_preempt = TB_NIL;
2819 	vcpu->arch.shregs.msr = MSR_ME;
2820 	vcpu->arch.intr_msr = MSR_SF | MSR_ME;
2821 
2822 	/*
2823 	 * Set the default HFSCR for the guest from the host value.
2824 	 * This value is only used on POWER9.
2825 	 * On POWER9, we want to virtualize the doorbell facility, so we
2826 	 * don't set the HFSCR_MSGP bit, and that causes those instructions
2827 	 * to trap and then we emulate them.
2828 	 */
2829 	vcpu->arch.hfscr = HFSCR_TAR | HFSCR_EBB | HFSCR_PM | HFSCR_BHRB |
2830 		HFSCR_DSCR | HFSCR_VECVSX | HFSCR_FP | HFSCR_PREFIX;
2831 	if (cpu_has_feature(CPU_FTR_HVMODE)) {
2832 		vcpu->arch.hfscr &= mfspr(SPRN_HFSCR);
2833 #ifdef CONFIG_PPC_TRANSACTIONAL_MEM
2834 		if (cpu_has_feature(CPU_FTR_P9_TM_HV_ASSIST))
2835 			vcpu->arch.hfscr |= HFSCR_TM;
2836 #endif
2837 	}
2838 	if (cpu_has_feature(CPU_FTR_TM_COMP))
2839 		vcpu->arch.hfscr |= HFSCR_TM;
2840 
2841 	vcpu->arch.hfscr_permitted = vcpu->arch.hfscr;
2842 
2843 	/*
2844 	 * PM, EBB, TM are demand-faulted so start with it clear.
2845 	 */
2846 	vcpu->arch.hfscr &= ~(HFSCR_PM | HFSCR_EBB | HFSCR_TM);
2847 
2848 	kvmppc_mmu_book3s_hv_init(vcpu);
2849 
2850 	vcpu->arch.state = KVMPPC_VCPU_NOTREADY;
2851 
2852 	init_waitqueue_head(&vcpu->arch.cpu_run);
2853 
2854 	mutex_lock(&kvm->lock);
2855 	vcore = NULL;
2856 	err = -EINVAL;
2857 	if (cpu_has_feature(CPU_FTR_ARCH_300)) {
2858 		if (id >= (KVM_MAX_VCPUS * kvm->arch.emul_smt_mode)) {
2859 			pr_devel("KVM: VCPU ID too high\n");
2860 			core = KVM_MAX_VCORES;
2861 		} else {
2862 			BUG_ON(kvm->arch.smt_mode != 1);
2863 			core = kvmppc_pack_vcpu_id(kvm, id);
2864 		}
2865 	} else {
2866 		core = id / kvm->arch.smt_mode;
2867 	}
2868 	if (core < KVM_MAX_VCORES) {
2869 		vcore = kvm->arch.vcores[core];
2870 		if (vcore && cpu_has_feature(CPU_FTR_ARCH_300)) {
2871 			pr_devel("KVM: collision on id %u", id);
2872 			vcore = NULL;
2873 		} else if (!vcore) {
2874 			/*
2875 			 * Take mmu_setup_lock for mutual exclusion
2876 			 * with kvmppc_update_lpcr().
2877 			 */
2878 			err = -ENOMEM;
2879 			vcore = kvmppc_vcore_create(kvm,
2880 					id & ~(kvm->arch.smt_mode - 1));
2881 			mutex_lock(&kvm->arch.mmu_setup_lock);
2882 			kvm->arch.vcores[core] = vcore;
2883 			kvm->arch.online_vcores++;
2884 			mutex_unlock(&kvm->arch.mmu_setup_lock);
2885 		}
2886 	}
2887 	mutex_unlock(&kvm->lock);
2888 
2889 	if (!vcore)
2890 		return err;
2891 
2892 	spin_lock(&vcore->lock);
2893 	++vcore->num_threads;
2894 	spin_unlock(&vcore->lock);
2895 	vcpu->arch.vcore = vcore;
2896 	vcpu->arch.ptid = vcpu->vcpu_id - vcore->first_vcpuid;
2897 	vcpu->arch.thread_cpu = -1;
2898 	vcpu->arch.prev_cpu = -1;
2899 
2900 	vcpu->arch.cpu_type = KVM_CPU_3S_64;
2901 	kvmppc_sanity_check(vcpu);
2902 
2903 	return 0;
2904 }
2905 
2906 static int kvmhv_set_smt_mode(struct kvm *kvm, unsigned long smt_mode,
2907 			      unsigned long flags)
2908 {
2909 	int err;
2910 	int esmt = 0;
2911 
2912 	if (flags)
2913 		return -EINVAL;
2914 	if (smt_mode > MAX_SMT_THREADS || !is_power_of_2(smt_mode))
2915 		return -EINVAL;
2916 	if (!cpu_has_feature(CPU_FTR_ARCH_300)) {
2917 		/*
2918 		 * On POWER8 (or POWER7), the threading mode is "strict",
2919 		 * so we pack smt_mode vcpus per vcore.
2920 		 */
2921 		if (smt_mode > threads_per_subcore)
2922 			return -EINVAL;
2923 	} else {
2924 		/*
2925 		 * On POWER9, the threading mode is "loose",
2926 		 * so each vcpu gets its own vcore.
2927 		 */
2928 		esmt = smt_mode;
2929 		smt_mode = 1;
2930 	}
2931 	mutex_lock(&kvm->lock);
2932 	err = -EBUSY;
2933 	if (!kvm->arch.online_vcores) {
2934 		kvm->arch.smt_mode = smt_mode;
2935 		kvm->arch.emul_smt_mode = esmt;
2936 		err = 0;
2937 	}
2938 	mutex_unlock(&kvm->lock);
2939 
2940 	return err;
2941 }
2942 
2943 static void unpin_vpa(struct kvm *kvm, struct kvmppc_vpa *vpa)
2944 {
2945 	if (vpa->pinned_addr)
2946 		kvmppc_unpin_guest_page(kvm, vpa->pinned_addr, vpa->gpa,
2947 					vpa->dirty);
2948 }
2949 
2950 static void kvmppc_core_vcpu_free_hv(struct kvm_vcpu *vcpu)
2951 {
2952 	spin_lock(&vcpu->arch.vpa_update_lock);
2953 	unpin_vpa(vcpu->kvm, &vcpu->arch.dtl);
2954 	unpin_vpa(vcpu->kvm, &vcpu->arch.slb_shadow);
2955 	unpin_vpa(vcpu->kvm, &vcpu->arch.vpa);
2956 	spin_unlock(&vcpu->arch.vpa_update_lock);
2957 }
2958 
2959 static int kvmppc_core_check_requests_hv(struct kvm_vcpu *vcpu)
2960 {
2961 	/* Indicate we want to get back into the guest */
2962 	return 1;
2963 }
2964 
2965 static void kvmppc_set_timer(struct kvm_vcpu *vcpu)
2966 {
2967 	unsigned long dec_nsec, now;
2968 
2969 	now = get_tb();
2970 	if (now > kvmppc_dec_expires_host_tb(vcpu)) {
2971 		/* decrementer has already gone negative */
2972 		kvmppc_core_queue_dec(vcpu);
2973 		kvmppc_core_prepare_to_enter(vcpu);
2974 		return;
2975 	}
2976 	dec_nsec = tb_to_ns(kvmppc_dec_expires_host_tb(vcpu) - now);
2977 	hrtimer_start(&vcpu->arch.dec_timer, dec_nsec, HRTIMER_MODE_REL);
2978 	vcpu->arch.timer_running = 1;
2979 }
2980 
2981 extern int __kvmppc_vcore_entry(void);
2982 
2983 static void kvmppc_remove_runnable(struct kvmppc_vcore *vc,
2984 				   struct kvm_vcpu *vcpu, u64 tb)
2985 {
2986 	u64 now;
2987 
2988 	if (vcpu->arch.state != KVMPPC_VCPU_RUNNABLE)
2989 		return;
2990 	spin_lock_irq(&vcpu->arch.tbacct_lock);
2991 	now = tb;
2992 	vcpu->arch.busy_stolen += vcore_stolen_time(vc, now) -
2993 		vcpu->arch.stolen_logged;
2994 	vcpu->arch.busy_preempt = now;
2995 	vcpu->arch.state = KVMPPC_VCPU_BUSY_IN_HOST;
2996 	spin_unlock_irq(&vcpu->arch.tbacct_lock);
2997 	--vc->n_runnable;
2998 	WRITE_ONCE(vc->runnable_threads[vcpu->arch.ptid], NULL);
2999 }
3000 
3001 static int kvmppc_grab_hwthread(int cpu)
3002 {
3003 	struct paca_struct *tpaca;
3004 	long timeout = 10000;
3005 
3006 	tpaca = paca_ptrs[cpu];
3007 
3008 	/* Ensure the thread won't go into the kernel if it wakes */
3009 	tpaca->kvm_hstate.kvm_vcpu = NULL;
3010 	tpaca->kvm_hstate.kvm_vcore = NULL;
3011 	tpaca->kvm_hstate.napping = 0;
3012 	smp_wmb();
3013 	tpaca->kvm_hstate.hwthread_req = 1;
3014 
3015 	/*
3016 	 * If the thread is already executing in the kernel (e.g. handling
3017 	 * a stray interrupt), wait for it to get back to nap mode.
3018 	 * The smp_mb() is to ensure that our setting of hwthread_req
3019 	 * is visible before we look at hwthread_state, so if this
3020 	 * races with the code at system_reset_pSeries and the thread
3021 	 * misses our setting of hwthread_req, we are sure to see its
3022 	 * setting of hwthread_state, and vice versa.
3023 	 */
3024 	smp_mb();
3025 	while (tpaca->kvm_hstate.hwthread_state == KVM_HWTHREAD_IN_KERNEL) {
3026 		if (--timeout <= 0) {
3027 			pr_err("KVM: couldn't grab cpu %d\n", cpu);
3028 			return -EBUSY;
3029 		}
3030 		udelay(1);
3031 	}
3032 	return 0;
3033 }
3034 
3035 static void kvmppc_release_hwthread(int cpu)
3036 {
3037 	struct paca_struct *tpaca;
3038 
3039 	tpaca = paca_ptrs[cpu];
3040 	tpaca->kvm_hstate.hwthread_req = 0;
3041 	tpaca->kvm_hstate.kvm_vcpu = NULL;
3042 	tpaca->kvm_hstate.kvm_vcore = NULL;
3043 	tpaca->kvm_hstate.kvm_split_mode = NULL;
3044 }
3045 
3046 static DEFINE_PER_CPU(struct kvm *, cpu_in_guest);
3047 
3048 static void radix_flush_cpu(struct kvm *kvm, int cpu, struct kvm_vcpu *vcpu)
3049 {
3050 	struct kvm_nested_guest *nested = vcpu->arch.nested;
3051 	cpumask_t *need_tlb_flush;
3052 	int i;
3053 
3054 	if (nested)
3055 		need_tlb_flush = &nested->need_tlb_flush;
3056 	else
3057 		need_tlb_flush = &kvm->arch.need_tlb_flush;
3058 
3059 	cpu = cpu_first_tlb_thread_sibling(cpu);
3060 	for (i = cpu; i <= cpu_last_tlb_thread_sibling(cpu);
3061 					i += cpu_tlb_thread_sibling_step())
3062 		cpumask_set_cpu(i, need_tlb_flush);
3063 
3064 	/*
3065 	 * Make sure setting of bit in need_tlb_flush precedes testing of
3066 	 * cpu_in_guest. The matching barrier on the other side is hwsync
3067 	 * when switching to guest MMU mode, which happens between
3068 	 * cpu_in_guest being set to the guest kvm, and need_tlb_flush bit
3069 	 * being tested.
3070 	 */
3071 	smp_mb();
3072 
3073 	for (i = cpu; i <= cpu_last_tlb_thread_sibling(cpu);
3074 					i += cpu_tlb_thread_sibling_step()) {
3075 		struct kvm *running = *per_cpu_ptr(&cpu_in_guest, i);
3076 
3077 		if (running == kvm)
3078 			smp_call_function_single(i, do_nothing, NULL, 1);
3079 	}
3080 }
3081 
3082 static void do_migrate_away_vcpu(void *arg)
3083 {
3084 	struct kvm_vcpu *vcpu = arg;
3085 	struct kvm *kvm = vcpu->kvm;
3086 
3087 	/*
3088 	 * If the guest has GTSE, it may execute tlbie, so do a eieio; tlbsync;
3089 	 * ptesync sequence on the old CPU before migrating to a new one, in
3090 	 * case we interrupted the guest between a tlbie ; eieio ;
3091 	 * tlbsync; ptesync sequence.
3092 	 *
3093 	 * Otherwise, ptesync is sufficient for ordering tlbiel sequences.
3094 	 */
3095 	if (kvm->arch.lpcr & LPCR_GTSE)
3096 		asm volatile("eieio; tlbsync; ptesync");
3097 	else
3098 		asm volatile("ptesync");
3099 }
3100 
3101 static void kvmppc_prepare_radix_vcpu(struct kvm_vcpu *vcpu, int pcpu)
3102 {
3103 	struct kvm_nested_guest *nested = vcpu->arch.nested;
3104 	struct kvm *kvm = vcpu->kvm;
3105 	int prev_cpu;
3106 
3107 	if (!cpu_has_feature(CPU_FTR_HVMODE))
3108 		return;
3109 
3110 	if (nested)
3111 		prev_cpu = nested->prev_cpu[vcpu->arch.nested_vcpu_id];
3112 	else
3113 		prev_cpu = vcpu->arch.prev_cpu;
3114 
3115 	/*
3116 	 * With radix, the guest can do TLB invalidations itself,
3117 	 * and it could choose to use the local form (tlbiel) if
3118 	 * it is invalidating a translation that has only ever been
3119 	 * used on one vcpu.  However, that doesn't mean it has
3120 	 * only ever been used on one physical cpu, since vcpus
3121 	 * can move around between pcpus.  To cope with this, when
3122 	 * a vcpu moves from one pcpu to another, we need to tell
3123 	 * any vcpus running on the same core as this vcpu previously
3124 	 * ran to flush the TLB.
3125 	 */
3126 	if (prev_cpu != pcpu) {
3127 		if (prev_cpu >= 0) {
3128 			if (cpu_first_tlb_thread_sibling(prev_cpu) !=
3129 			    cpu_first_tlb_thread_sibling(pcpu))
3130 				radix_flush_cpu(kvm, prev_cpu, vcpu);
3131 
3132 			smp_call_function_single(prev_cpu,
3133 					do_migrate_away_vcpu, vcpu, 1);
3134 		}
3135 		if (nested)
3136 			nested->prev_cpu[vcpu->arch.nested_vcpu_id] = pcpu;
3137 		else
3138 			vcpu->arch.prev_cpu = pcpu;
3139 	}
3140 }
3141 
3142 static void kvmppc_start_thread(struct kvm_vcpu *vcpu, struct kvmppc_vcore *vc)
3143 {
3144 	int cpu;
3145 	struct paca_struct *tpaca;
3146 
3147 	cpu = vc->pcpu;
3148 	if (vcpu) {
3149 		if (vcpu->arch.timer_running) {
3150 			hrtimer_try_to_cancel(&vcpu->arch.dec_timer);
3151 			vcpu->arch.timer_running = 0;
3152 		}
3153 		cpu += vcpu->arch.ptid;
3154 		vcpu->cpu = vc->pcpu;
3155 		vcpu->arch.thread_cpu = cpu;
3156 	}
3157 	tpaca = paca_ptrs[cpu];
3158 	tpaca->kvm_hstate.kvm_vcpu = vcpu;
3159 	tpaca->kvm_hstate.ptid = cpu - vc->pcpu;
3160 	tpaca->kvm_hstate.fake_suspend = 0;
3161 	/* Order stores to hstate.kvm_vcpu etc. before store to kvm_vcore */
3162 	smp_wmb();
3163 	tpaca->kvm_hstate.kvm_vcore = vc;
3164 	if (cpu != smp_processor_id())
3165 		kvmppc_ipi_thread(cpu);
3166 }
3167 
3168 static void kvmppc_wait_for_nap(int n_threads)
3169 {
3170 	int cpu = smp_processor_id();
3171 	int i, loops;
3172 
3173 	if (n_threads <= 1)
3174 		return;
3175 	for (loops = 0; loops < 1000000; ++loops) {
3176 		/*
3177 		 * Check if all threads are finished.
3178 		 * We set the vcore pointer when starting a thread
3179 		 * and the thread clears it when finished, so we look
3180 		 * for any threads that still have a non-NULL vcore ptr.
3181 		 */
3182 		for (i = 1; i < n_threads; ++i)
3183 			if (paca_ptrs[cpu + i]->kvm_hstate.kvm_vcore)
3184 				break;
3185 		if (i == n_threads) {
3186 			HMT_medium();
3187 			return;
3188 		}
3189 		HMT_low();
3190 	}
3191 	HMT_medium();
3192 	for (i = 1; i < n_threads; ++i)
3193 		if (paca_ptrs[cpu + i]->kvm_hstate.kvm_vcore)
3194 			pr_err("KVM: CPU %d seems to be stuck\n", cpu + i);
3195 }
3196 
3197 /*
3198  * Check that we are on thread 0 and that any other threads in
3199  * this core are off-line.  Then grab the threads so they can't
3200  * enter the kernel.
3201  */
3202 static int on_primary_thread(void)
3203 {
3204 	int cpu = smp_processor_id();
3205 	int thr;
3206 
3207 	/* Are we on a primary subcore? */
3208 	if (cpu_thread_in_subcore(cpu))
3209 		return 0;
3210 
3211 	thr = 0;
3212 	while (++thr < threads_per_subcore)
3213 		if (cpu_online(cpu + thr))
3214 			return 0;
3215 
3216 	/* Grab all hw threads so they can't go into the kernel */
3217 	for (thr = 1; thr < threads_per_subcore; ++thr) {
3218 		if (kvmppc_grab_hwthread(cpu + thr)) {
3219 			/* Couldn't grab one; let the others go */
3220 			do {
3221 				kvmppc_release_hwthread(cpu + thr);
3222 			} while (--thr > 0);
3223 			return 0;
3224 		}
3225 	}
3226 	return 1;
3227 }
3228 
3229 /*
3230  * A list of virtual cores for each physical CPU.
3231  * These are vcores that could run but their runner VCPU tasks are
3232  * (or may be) preempted.
3233  */
3234 struct preempted_vcore_list {
3235 	struct list_head	list;
3236 	spinlock_t		lock;
3237 };
3238 
3239 static DEFINE_PER_CPU(struct preempted_vcore_list, preempted_vcores);
3240 
3241 static void init_vcore_lists(void)
3242 {
3243 	int cpu;
3244 
3245 	for_each_possible_cpu(cpu) {
3246 		struct preempted_vcore_list *lp = &per_cpu(preempted_vcores, cpu);
3247 		spin_lock_init(&lp->lock);
3248 		INIT_LIST_HEAD(&lp->list);
3249 	}
3250 }
3251 
3252 static void kvmppc_vcore_preempt(struct kvmppc_vcore *vc)
3253 {
3254 	struct preempted_vcore_list *lp = this_cpu_ptr(&preempted_vcores);
3255 
3256 	WARN_ON_ONCE(cpu_has_feature(CPU_FTR_ARCH_300));
3257 
3258 	vc->vcore_state = VCORE_PREEMPT;
3259 	vc->pcpu = smp_processor_id();
3260 	if (vc->num_threads < threads_per_vcore(vc->kvm)) {
3261 		spin_lock(&lp->lock);
3262 		list_add_tail(&vc->preempt_list, &lp->list);
3263 		spin_unlock(&lp->lock);
3264 	}
3265 
3266 	/* Start accumulating stolen time */
3267 	kvmppc_core_start_stolen(vc, mftb());
3268 }
3269 
3270 static void kvmppc_vcore_end_preempt(struct kvmppc_vcore *vc)
3271 {
3272 	struct preempted_vcore_list *lp;
3273 
3274 	WARN_ON_ONCE(cpu_has_feature(CPU_FTR_ARCH_300));
3275 
3276 	kvmppc_core_end_stolen(vc, mftb());
3277 	if (!list_empty(&vc->preempt_list)) {
3278 		lp = &per_cpu(preempted_vcores, vc->pcpu);
3279 		spin_lock(&lp->lock);
3280 		list_del_init(&vc->preempt_list);
3281 		spin_unlock(&lp->lock);
3282 	}
3283 	vc->vcore_state = VCORE_INACTIVE;
3284 }
3285 
3286 /*
3287  * This stores information about the virtual cores currently
3288  * assigned to a physical core.
3289  */
3290 struct core_info {
3291 	int		n_subcores;
3292 	int		max_subcore_threads;
3293 	int		total_threads;
3294 	int		subcore_threads[MAX_SUBCORES];
3295 	struct kvmppc_vcore *vc[MAX_SUBCORES];
3296 };
3297 
3298 /*
3299  * This mapping means subcores 0 and 1 can use threads 0-3 and 4-7
3300  * respectively in 2-way micro-threading (split-core) mode on POWER8.
3301  */
3302 static int subcore_thread_map[MAX_SUBCORES] = { 0, 4, 2, 6 };
3303 
3304 static void init_core_info(struct core_info *cip, struct kvmppc_vcore *vc)
3305 {
3306 	memset(cip, 0, sizeof(*cip));
3307 	cip->n_subcores = 1;
3308 	cip->max_subcore_threads = vc->num_threads;
3309 	cip->total_threads = vc->num_threads;
3310 	cip->subcore_threads[0] = vc->num_threads;
3311 	cip->vc[0] = vc;
3312 }
3313 
3314 static bool subcore_config_ok(int n_subcores, int n_threads)
3315 {
3316 	/*
3317 	 * POWER9 "SMT4" cores are permanently in what is effectively a 4-way
3318 	 * split-core mode, with one thread per subcore.
3319 	 */
3320 	if (cpu_has_feature(CPU_FTR_ARCH_300))
3321 		return n_subcores <= 4 && n_threads == 1;
3322 
3323 	/* On POWER8, can only dynamically split if unsplit to begin with */
3324 	if (n_subcores > 1 && threads_per_subcore < MAX_SMT_THREADS)
3325 		return false;
3326 	if (n_subcores > MAX_SUBCORES)
3327 		return false;
3328 	if (n_subcores > 1) {
3329 		if (!(dynamic_mt_modes & 2))
3330 			n_subcores = 4;
3331 		if (n_subcores > 2 && !(dynamic_mt_modes & 4))
3332 			return false;
3333 	}
3334 
3335 	return n_subcores * roundup_pow_of_two(n_threads) <= MAX_SMT_THREADS;
3336 }
3337 
3338 static void init_vcore_to_run(struct kvmppc_vcore *vc)
3339 {
3340 	vc->entry_exit_map = 0;
3341 	vc->in_guest = 0;
3342 	vc->napping_threads = 0;
3343 	vc->conferring_threads = 0;
3344 	vc->tb_offset_applied = 0;
3345 }
3346 
3347 static bool can_dynamic_split(struct kvmppc_vcore *vc, struct core_info *cip)
3348 {
3349 	int n_threads = vc->num_threads;
3350 	int sub;
3351 
3352 	if (!cpu_has_feature(CPU_FTR_ARCH_207S))
3353 		return false;
3354 
3355 	/* In one_vm_per_core mode, require all vcores to be from the same vm */
3356 	if (one_vm_per_core && vc->kvm != cip->vc[0]->kvm)
3357 		return false;
3358 
3359 	if (n_threads < cip->max_subcore_threads)
3360 		n_threads = cip->max_subcore_threads;
3361 	if (!subcore_config_ok(cip->n_subcores + 1, n_threads))
3362 		return false;
3363 	cip->max_subcore_threads = n_threads;
3364 
3365 	sub = cip->n_subcores;
3366 	++cip->n_subcores;
3367 	cip->total_threads += vc->num_threads;
3368 	cip->subcore_threads[sub] = vc->num_threads;
3369 	cip->vc[sub] = vc;
3370 	init_vcore_to_run(vc);
3371 	list_del_init(&vc->preempt_list);
3372 
3373 	return true;
3374 }
3375 
3376 /*
3377  * Work out whether it is possible to piggyback the execution of
3378  * vcore *pvc onto the execution of the other vcores described in *cip.
3379  */
3380 static bool can_piggyback(struct kvmppc_vcore *pvc, struct core_info *cip,
3381 			  int target_threads)
3382 {
3383 	if (cip->total_threads + pvc->num_threads > target_threads)
3384 		return false;
3385 
3386 	return can_dynamic_split(pvc, cip);
3387 }
3388 
3389 static void prepare_threads(struct kvmppc_vcore *vc)
3390 {
3391 	int i;
3392 	struct kvm_vcpu *vcpu;
3393 
3394 	for_each_runnable_thread(i, vcpu, vc) {
3395 		if (signal_pending(vcpu->arch.run_task))
3396 			vcpu->arch.ret = -EINTR;
3397 		else if (vcpu->arch.vpa.update_pending ||
3398 			 vcpu->arch.slb_shadow.update_pending ||
3399 			 vcpu->arch.dtl.update_pending)
3400 			vcpu->arch.ret = RESUME_GUEST;
3401 		else
3402 			continue;
3403 		kvmppc_remove_runnable(vc, vcpu, mftb());
3404 		wake_up(&vcpu->arch.cpu_run);
3405 	}
3406 }
3407 
3408 static void collect_piggybacks(struct core_info *cip, int target_threads)
3409 {
3410 	struct preempted_vcore_list *lp = this_cpu_ptr(&preempted_vcores);
3411 	struct kvmppc_vcore *pvc, *vcnext;
3412 
3413 	spin_lock(&lp->lock);
3414 	list_for_each_entry_safe(pvc, vcnext, &lp->list, preempt_list) {
3415 		if (!spin_trylock(&pvc->lock))
3416 			continue;
3417 		prepare_threads(pvc);
3418 		if (!pvc->n_runnable || !pvc->kvm->arch.mmu_ready) {
3419 			list_del_init(&pvc->preempt_list);
3420 			if (pvc->runner == NULL) {
3421 				pvc->vcore_state = VCORE_INACTIVE;
3422 				kvmppc_core_end_stolen(pvc, mftb());
3423 			}
3424 			spin_unlock(&pvc->lock);
3425 			continue;
3426 		}
3427 		if (!can_piggyback(pvc, cip, target_threads)) {
3428 			spin_unlock(&pvc->lock);
3429 			continue;
3430 		}
3431 		kvmppc_core_end_stolen(pvc, mftb());
3432 		pvc->vcore_state = VCORE_PIGGYBACK;
3433 		if (cip->total_threads >= target_threads)
3434 			break;
3435 	}
3436 	spin_unlock(&lp->lock);
3437 }
3438 
3439 static bool recheck_signals_and_mmu(struct core_info *cip)
3440 {
3441 	int sub, i;
3442 	struct kvm_vcpu *vcpu;
3443 	struct kvmppc_vcore *vc;
3444 
3445 	for (sub = 0; sub < cip->n_subcores; ++sub) {
3446 		vc = cip->vc[sub];
3447 		if (!vc->kvm->arch.mmu_ready)
3448 			return true;
3449 		for_each_runnable_thread(i, vcpu, vc)
3450 			if (signal_pending(vcpu->arch.run_task))
3451 				return true;
3452 	}
3453 	return false;
3454 }
3455 
3456 static void post_guest_process(struct kvmppc_vcore *vc, bool is_master)
3457 {
3458 	int still_running = 0, i;
3459 	u64 now;
3460 	long ret;
3461 	struct kvm_vcpu *vcpu;
3462 
3463 	spin_lock(&vc->lock);
3464 	now = get_tb();
3465 	for_each_runnable_thread(i, vcpu, vc) {
3466 		/*
3467 		 * It's safe to unlock the vcore in the loop here, because
3468 		 * for_each_runnable_thread() is safe against removal of
3469 		 * the vcpu, and the vcore state is VCORE_EXITING here,
3470 		 * so any vcpus becoming runnable will have their arch.trap
3471 		 * set to zero and can't actually run in the guest.
3472 		 */
3473 		spin_unlock(&vc->lock);
3474 		/* cancel pending dec exception if dec is positive */
3475 		if (now < kvmppc_dec_expires_host_tb(vcpu) &&
3476 		    kvmppc_core_pending_dec(vcpu))
3477 			kvmppc_core_dequeue_dec(vcpu);
3478 
3479 		trace_kvm_guest_exit(vcpu);
3480 
3481 		ret = RESUME_GUEST;
3482 		if (vcpu->arch.trap)
3483 			ret = kvmppc_handle_exit_hv(vcpu,
3484 						    vcpu->arch.run_task);
3485 
3486 		vcpu->arch.ret = ret;
3487 		vcpu->arch.trap = 0;
3488 
3489 		spin_lock(&vc->lock);
3490 		if (is_kvmppc_resume_guest(vcpu->arch.ret)) {
3491 			if (vcpu->arch.pending_exceptions)
3492 				kvmppc_core_prepare_to_enter(vcpu);
3493 			if (vcpu->arch.ceded)
3494 				kvmppc_set_timer(vcpu);
3495 			else
3496 				++still_running;
3497 		} else {
3498 			kvmppc_remove_runnable(vc, vcpu, mftb());
3499 			wake_up(&vcpu->arch.cpu_run);
3500 		}
3501 	}
3502 	if (!is_master) {
3503 		if (still_running > 0) {
3504 			kvmppc_vcore_preempt(vc);
3505 		} else if (vc->runner) {
3506 			vc->vcore_state = VCORE_PREEMPT;
3507 			kvmppc_core_start_stolen(vc, mftb());
3508 		} else {
3509 			vc->vcore_state = VCORE_INACTIVE;
3510 		}
3511 		if (vc->n_runnable > 0 && vc->runner == NULL) {
3512 			/* make sure there's a candidate runner awake */
3513 			i = -1;
3514 			vcpu = next_runnable_thread(vc, &i);
3515 			wake_up(&vcpu->arch.cpu_run);
3516 		}
3517 	}
3518 	spin_unlock(&vc->lock);
3519 }
3520 
3521 /*
3522  * Clear core from the list of active host cores as we are about to
3523  * enter the guest. Only do this if it is the primary thread of the
3524  * core (not if a subcore) that is entering the guest.
3525  */
3526 static inline int kvmppc_clear_host_core(unsigned int cpu)
3527 {
3528 	int core;
3529 
3530 	if (!kvmppc_host_rm_ops_hv || cpu_thread_in_core(cpu))
3531 		return 0;
3532 	/*
3533 	 * Memory barrier can be omitted here as we will do a smp_wmb()
3534 	 * later in kvmppc_start_thread and we need ensure that state is
3535 	 * visible to other CPUs only after we enter guest.
3536 	 */
3537 	core = cpu >> threads_shift;
3538 	kvmppc_host_rm_ops_hv->rm_core[core].rm_state.in_host = 0;
3539 	return 0;
3540 }
3541 
3542 /*
3543  * Advertise this core as an active host core since we exited the guest
3544  * Only need to do this if it is the primary thread of the core that is
3545  * exiting.
3546  */
3547 static inline int kvmppc_set_host_core(unsigned int cpu)
3548 {
3549 	int core;
3550 
3551 	if (!kvmppc_host_rm_ops_hv || cpu_thread_in_core(cpu))
3552 		return 0;
3553 
3554 	/*
3555 	 * Memory barrier can be omitted here because we do a spin_unlock
3556 	 * immediately after this which provides the memory barrier.
3557 	 */
3558 	core = cpu >> threads_shift;
3559 	kvmppc_host_rm_ops_hv->rm_core[core].rm_state.in_host = 1;
3560 	return 0;
3561 }
3562 
3563 static void set_irq_happened(int trap)
3564 {
3565 	switch (trap) {
3566 	case BOOK3S_INTERRUPT_EXTERNAL:
3567 		local_paca->irq_happened |= PACA_IRQ_EE;
3568 		break;
3569 	case BOOK3S_INTERRUPT_H_DOORBELL:
3570 		local_paca->irq_happened |= PACA_IRQ_DBELL;
3571 		break;
3572 	case BOOK3S_INTERRUPT_HMI:
3573 		local_paca->irq_happened |= PACA_IRQ_HMI;
3574 		break;
3575 	case BOOK3S_INTERRUPT_SYSTEM_RESET:
3576 		replay_system_reset();
3577 		break;
3578 	}
3579 }
3580 
3581 /*
3582  * Run a set of guest threads on a physical core.
3583  * Called with vc->lock held.
3584  */
3585 static noinline void kvmppc_run_core(struct kvmppc_vcore *vc)
3586 {
3587 	struct kvm_vcpu *vcpu;
3588 	int i;
3589 	int srcu_idx;
3590 	struct core_info core_info;
3591 	struct kvmppc_vcore *pvc;
3592 	struct kvm_split_mode split_info, *sip;
3593 	int split, subcore_size, active;
3594 	int sub;
3595 	bool thr0_done;
3596 	unsigned long cmd_bit, stat_bit;
3597 	int pcpu, thr;
3598 	int target_threads;
3599 	int controlled_threads;
3600 	int trap;
3601 	bool is_power8;
3602 
3603 	if (WARN_ON_ONCE(cpu_has_feature(CPU_FTR_ARCH_300)))
3604 		return;
3605 
3606 	/*
3607 	 * Remove from the list any threads that have a signal pending
3608 	 * or need a VPA update done
3609 	 */
3610 	prepare_threads(vc);
3611 
3612 	/* if the runner is no longer runnable, let the caller pick a new one */
3613 	if (vc->runner->arch.state != KVMPPC_VCPU_RUNNABLE)
3614 		return;
3615 
3616 	/*
3617 	 * Initialize *vc.
3618 	 */
3619 	init_vcore_to_run(vc);
3620 	vc->preempt_tb = TB_NIL;
3621 
3622 	/*
3623 	 * Number of threads that we will be controlling: the same as
3624 	 * the number of threads per subcore, except on POWER9,
3625 	 * where it's 1 because the threads are (mostly) independent.
3626 	 */
3627 	controlled_threads = threads_per_vcore(vc->kvm);
3628 
3629 	/*
3630 	 * Make sure we are running on primary threads, and that secondary
3631 	 * threads are offline.  Also check if the number of threads in this
3632 	 * guest are greater than the current system threads per guest.
3633 	 */
3634 	if ((controlled_threads > 1) &&
3635 	    ((vc->num_threads > threads_per_subcore) || !on_primary_thread())) {
3636 		for_each_runnable_thread(i, vcpu, vc) {
3637 			vcpu->arch.ret = -EBUSY;
3638 			kvmppc_remove_runnable(vc, vcpu, mftb());
3639 			wake_up(&vcpu->arch.cpu_run);
3640 		}
3641 		goto out;
3642 	}
3643 
3644 	/*
3645 	 * See if we could run any other vcores on the physical core
3646 	 * along with this one.
3647 	 */
3648 	init_core_info(&core_info, vc);
3649 	pcpu = smp_processor_id();
3650 	target_threads = controlled_threads;
3651 	if (target_smt_mode && target_smt_mode < target_threads)
3652 		target_threads = target_smt_mode;
3653 	if (vc->num_threads < target_threads)
3654 		collect_piggybacks(&core_info, target_threads);
3655 
3656 	/*
3657 	 * Hard-disable interrupts, and check resched flag and signals.
3658 	 * If we need to reschedule or deliver a signal, clean up
3659 	 * and return without going into the guest(s).
3660 	 * If the mmu_ready flag has been cleared, don't go into the
3661 	 * guest because that means a HPT resize operation is in progress.
3662 	 */
3663 	local_irq_disable();
3664 	hard_irq_disable();
3665 	if (lazy_irq_pending() || need_resched() ||
3666 	    recheck_signals_and_mmu(&core_info)) {
3667 		local_irq_enable();
3668 		vc->vcore_state = VCORE_INACTIVE;
3669 		/* Unlock all except the primary vcore */
3670 		for (sub = 1; sub < core_info.n_subcores; ++sub) {
3671 			pvc = core_info.vc[sub];
3672 			/* Put back on to the preempted vcores list */
3673 			kvmppc_vcore_preempt(pvc);
3674 			spin_unlock(&pvc->lock);
3675 		}
3676 		for (i = 0; i < controlled_threads; ++i)
3677 			kvmppc_release_hwthread(pcpu + i);
3678 		return;
3679 	}
3680 
3681 	kvmppc_clear_host_core(pcpu);
3682 
3683 	/* Decide on micro-threading (split-core) mode */
3684 	subcore_size = threads_per_subcore;
3685 	cmd_bit = stat_bit = 0;
3686 	split = core_info.n_subcores;
3687 	sip = NULL;
3688 	is_power8 = cpu_has_feature(CPU_FTR_ARCH_207S);
3689 
3690 	if (split > 1) {
3691 		sip = &split_info;
3692 		memset(&split_info, 0, sizeof(split_info));
3693 		for (sub = 0; sub < core_info.n_subcores; ++sub)
3694 			split_info.vc[sub] = core_info.vc[sub];
3695 
3696 		if (is_power8) {
3697 			if (split == 2 && (dynamic_mt_modes & 2)) {
3698 				cmd_bit = HID0_POWER8_1TO2LPAR;
3699 				stat_bit = HID0_POWER8_2LPARMODE;
3700 			} else {
3701 				split = 4;
3702 				cmd_bit = HID0_POWER8_1TO4LPAR;
3703 				stat_bit = HID0_POWER8_4LPARMODE;
3704 			}
3705 			subcore_size = MAX_SMT_THREADS / split;
3706 			split_info.rpr = mfspr(SPRN_RPR);
3707 			split_info.pmmar = mfspr(SPRN_PMMAR);
3708 			split_info.ldbar = mfspr(SPRN_LDBAR);
3709 			split_info.subcore_size = subcore_size;
3710 		} else {
3711 			split_info.subcore_size = 1;
3712 		}
3713 
3714 		/* order writes to split_info before kvm_split_mode pointer */
3715 		smp_wmb();
3716 	}
3717 
3718 	for (thr = 0; thr < controlled_threads; ++thr) {
3719 		struct paca_struct *paca = paca_ptrs[pcpu + thr];
3720 
3721 		paca->kvm_hstate.napping = 0;
3722 		paca->kvm_hstate.kvm_split_mode = sip;
3723 	}
3724 
3725 	/* Initiate micro-threading (split-core) on POWER8 if required */
3726 	if (cmd_bit) {
3727 		unsigned long hid0 = mfspr(SPRN_HID0);
3728 
3729 		hid0 |= cmd_bit | HID0_POWER8_DYNLPARDIS;
3730 		mb();
3731 		mtspr(SPRN_HID0, hid0);
3732 		isync();
3733 		for (;;) {
3734 			hid0 = mfspr(SPRN_HID0);
3735 			if (hid0 & stat_bit)
3736 				break;
3737 			cpu_relax();
3738 		}
3739 	}
3740 
3741 	/*
3742 	 * On POWER8, set RWMR register.
3743 	 * Since it only affects PURR and SPURR, it doesn't affect
3744 	 * the host, so we don't save/restore the host value.
3745 	 */
3746 	if (is_power8) {
3747 		unsigned long rwmr_val = RWMR_RPA_P8_8THREAD;
3748 		int n_online = atomic_read(&vc->online_count);
3749 
3750 		/*
3751 		 * Use the 8-thread value if we're doing split-core
3752 		 * or if the vcore's online count looks bogus.
3753 		 */
3754 		if (split == 1 && threads_per_subcore == MAX_SMT_THREADS &&
3755 		    n_online >= 1 && n_online <= MAX_SMT_THREADS)
3756 			rwmr_val = p8_rwmr_values[n_online];
3757 		mtspr(SPRN_RWMR, rwmr_val);
3758 	}
3759 
3760 	/* Start all the threads */
3761 	active = 0;
3762 	for (sub = 0; sub < core_info.n_subcores; ++sub) {
3763 		thr = is_power8 ? subcore_thread_map[sub] : sub;
3764 		thr0_done = false;
3765 		active |= 1 << thr;
3766 		pvc = core_info.vc[sub];
3767 		pvc->pcpu = pcpu + thr;
3768 		for_each_runnable_thread(i, vcpu, pvc) {
3769 			kvmppc_start_thread(vcpu, pvc);
3770 			kvmppc_create_dtl_entry(vcpu, pvc);
3771 			trace_kvm_guest_enter(vcpu);
3772 			if (!vcpu->arch.ptid)
3773 				thr0_done = true;
3774 			active |= 1 << (thr + vcpu->arch.ptid);
3775 		}
3776 		/*
3777 		 * We need to start the first thread of each subcore
3778 		 * even if it doesn't have a vcpu.
3779 		 */
3780 		if (!thr0_done)
3781 			kvmppc_start_thread(NULL, pvc);
3782 	}
3783 
3784 	/*
3785 	 * Ensure that split_info.do_nap is set after setting
3786 	 * the vcore pointer in the PACA of the secondaries.
3787 	 */
3788 	smp_mb();
3789 
3790 	/*
3791 	 * When doing micro-threading, poke the inactive threads as well.
3792 	 * This gets them to the nap instruction after kvm_do_nap,
3793 	 * which reduces the time taken to unsplit later.
3794 	 */
3795 	if (cmd_bit) {
3796 		split_info.do_nap = 1;	/* ask secondaries to nap when done */
3797 		for (thr = 1; thr < threads_per_subcore; ++thr)
3798 			if (!(active & (1 << thr)))
3799 				kvmppc_ipi_thread(pcpu + thr);
3800 	}
3801 
3802 	vc->vcore_state = VCORE_RUNNING;
3803 	preempt_disable();
3804 
3805 	trace_kvmppc_run_core(vc, 0);
3806 
3807 	for (sub = 0; sub < core_info.n_subcores; ++sub)
3808 		spin_unlock(&core_info.vc[sub]->lock);
3809 
3810 	guest_enter_irqoff();
3811 
3812 	srcu_idx = srcu_read_lock(&vc->kvm->srcu);
3813 
3814 	this_cpu_disable_ftrace();
3815 
3816 	/*
3817 	 * Interrupts will be enabled once we get into the guest,
3818 	 * so tell lockdep that we're about to enable interrupts.
3819 	 */
3820 	trace_hardirqs_on();
3821 
3822 	trap = __kvmppc_vcore_entry();
3823 
3824 	trace_hardirqs_off();
3825 
3826 	this_cpu_enable_ftrace();
3827 
3828 	srcu_read_unlock(&vc->kvm->srcu, srcu_idx);
3829 
3830 	set_irq_happened(trap);
3831 
3832 	spin_lock(&vc->lock);
3833 	/* prevent other vcpu threads from doing kvmppc_start_thread() now */
3834 	vc->vcore_state = VCORE_EXITING;
3835 
3836 	/* wait for secondary threads to finish writing their state to memory */
3837 	kvmppc_wait_for_nap(controlled_threads);
3838 
3839 	/* Return to whole-core mode if we split the core earlier */
3840 	if (cmd_bit) {
3841 		unsigned long hid0 = mfspr(SPRN_HID0);
3842 		unsigned long loops = 0;
3843 
3844 		hid0 &= ~HID0_POWER8_DYNLPARDIS;
3845 		stat_bit = HID0_POWER8_2LPARMODE | HID0_POWER8_4LPARMODE;
3846 		mb();
3847 		mtspr(SPRN_HID0, hid0);
3848 		isync();
3849 		for (;;) {
3850 			hid0 = mfspr(SPRN_HID0);
3851 			if (!(hid0 & stat_bit))
3852 				break;
3853 			cpu_relax();
3854 			++loops;
3855 		}
3856 		split_info.do_nap = 0;
3857 	}
3858 
3859 	kvmppc_set_host_core(pcpu);
3860 
3861 	context_tracking_guest_exit();
3862 	if (!vtime_accounting_enabled_this_cpu()) {
3863 		local_irq_enable();
3864 		/*
3865 		 * Service IRQs here before vtime_account_guest_exit() so any
3866 		 * ticks that occurred while running the guest are accounted to
3867 		 * the guest. If vtime accounting is enabled, accounting uses
3868 		 * TB rather than ticks, so it can be done without enabling
3869 		 * interrupts here, which has the problem that it accounts
3870 		 * interrupt processing overhead to the host.
3871 		 */
3872 		local_irq_disable();
3873 	}
3874 	vtime_account_guest_exit();
3875 
3876 	local_irq_enable();
3877 
3878 	/* Let secondaries go back to the offline loop */
3879 	for (i = 0; i < controlled_threads; ++i) {
3880 		kvmppc_release_hwthread(pcpu + i);
3881 		if (sip && sip->napped[i])
3882 			kvmppc_ipi_thread(pcpu + i);
3883 	}
3884 
3885 	spin_unlock(&vc->lock);
3886 
3887 	/* make sure updates to secondary vcpu structs are visible now */
3888 	smp_mb();
3889 
3890 	preempt_enable();
3891 
3892 	for (sub = 0; sub < core_info.n_subcores; ++sub) {
3893 		pvc = core_info.vc[sub];
3894 		post_guest_process(pvc, pvc == vc);
3895 	}
3896 
3897 	spin_lock(&vc->lock);
3898 
3899  out:
3900 	vc->vcore_state = VCORE_INACTIVE;
3901 	trace_kvmppc_run_core(vc, 1);
3902 }
3903 
3904 static inline bool hcall_is_xics(unsigned long req)
3905 {
3906 	return req == H_EOI || req == H_CPPR || req == H_IPI ||
3907 		req == H_IPOLL || req == H_XIRR || req == H_XIRR_X;
3908 }
3909 
3910 static void vcpu_vpa_increment_dispatch(struct kvm_vcpu *vcpu)
3911 {
3912 	struct lppaca *lp = vcpu->arch.vpa.pinned_addr;
3913 	if (lp) {
3914 		u32 yield_count = be32_to_cpu(lp->yield_count) + 1;
3915 		lp->yield_count = cpu_to_be32(yield_count);
3916 		vcpu->arch.vpa.dirty = 1;
3917 	}
3918 }
3919 
3920 /* call our hypervisor to load up HV regs and go */
3921 static int kvmhv_vcpu_entry_p9_nested(struct kvm_vcpu *vcpu, u64 time_limit, unsigned long lpcr, u64 *tb)
3922 {
3923 	struct kvmppc_vcore *vc = vcpu->arch.vcore;
3924 	unsigned long host_psscr;
3925 	unsigned long msr;
3926 	struct hv_guest_state hvregs;
3927 	struct p9_host_os_sprs host_os_sprs;
3928 	s64 dec;
3929 	int trap;
3930 
3931 	msr = mfmsr();
3932 
3933 	save_p9_host_os_sprs(&host_os_sprs);
3934 
3935 	/*
3936 	 * We need to save and restore the guest visible part of the
3937 	 * psscr (i.e. using SPRN_PSSCR_PR) since the hypervisor
3938 	 * doesn't do this for us. Note only required if pseries since
3939 	 * this is done in kvmhv_vcpu_entry_p9() below otherwise.
3940 	 */
3941 	host_psscr = mfspr(SPRN_PSSCR_PR);
3942 
3943 	kvmppc_msr_hard_disable_set_facilities(vcpu, msr);
3944 	if (lazy_irq_pending())
3945 		return 0;
3946 
3947 	if (unlikely(load_vcpu_state(vcpu, &host_os_sprs)))
3948 		msr = mfmsr(); /* TM restore can update msr */
3949 
3950 	if (vcpu->arch.psscr != host_psscr)
3951 		mtspr(SPRN_PSSCR_PR, vcpu->arch.psscr);
3952 
3953 	kvmhv_save_hv_regs(vcpu, &hvregs);
3954 	hvregs.lpcr = lpcr;
3955 	vcpu->arch.regs.msr = vcpu->arch.shregs.msr;
3956 	hvregs.version = HV_GUEST_STATE_VERSION;
3957 	if (vcpu->arch.nested) {
3958 		hvregs.lpid = vcpu->arch.nested->shadow_lpid;
3959 		hvregs.vcpu_token = vcpu->arch.nested_vcpu_id;
3960 	} else {
3961 		hvregs.lpid = vcpu->kvm->arch.lpid;
3962 		hvregs.vcpu_token = vcpu->vcpu_id;
3963 	}
3964 	hvregs.hdec_expiry = time_limit;
3965 
3966 	/*
3967 	 * When setting DEC, we must always deal with irq_work_raise
3968 	 * via NMI vs setting DEC. The problem occurs right as we
3969 	 * switch into guest mode if a NMI hits and sets pending work
3970 	 * and sets DEC, then that will apply to the guest and not
3971 	 * bring us back to the host.
3972 	 *
3973 	 * irq_work_raise could check a flag (or possibly LPCR[HDICE]
3974 	 * for example) and set HDEC to 1? That wouldn't solve the
3975 	 * nested hv case which needs to abort the hcall or zero the
3976 	 * time limit.
3977 	 *
3978 	 * XXX: Another day's problem.
3979 	 */
3980 	mtspr(SPRN_DEC, kvmppc_dec_expires_host_tb(vcpu) - *tb);
3981 
3982 	mtspr(SPRN_DAR, vcpu->arch.shregs.dar);
3983 	mtspr(SPRN_DSISR, vcpu->arch.shregs.dsisr);
3984 	switch_pmu_to_guest(vcpu, &host_os_sprs);
3985 	trap = plpar_hcall_norets(H_ENTER_NESTED, __pa(&hvregs),
3986 				  __pa(&vcpu->arch.regs));
3987 	kvmhv_restore_hv_return_state(vcpu, &hvregs);
3988 	switch_pmu_to_host(vcpu, &host_os_sprs);
3989 	vcpu->arch.shregs.msr = vcpu->arch.regs.msr;
3990 	vcpu->arch.shregs.dar = mfspr(SPRN_DAR);
3991 	vcpu->arch.shregs.dsisr = mfspr(SPRN_DSISR);
3992 	vcpu->arch.psscr = mfspr(SPRN_PSSCR_PR);
3993 
3994 	store_vcpu_state(vcpu);
3995 
3996 	dec = mfspr(SPRN_DEC);
3997 	if (!(lpcr & LPCR_LD)) /* Sign extend if not using large decrementer */
3998 		dec = (s32) dec;
3999 	*tb = mftb();
4000 	vcpu->arch.dec_expires = dec + (*tb + vc->tb_offset);
4001 
4002 	timer_rearm_host_dec(*tb);
4003 
4004 	restore_p9_host_os_sprs(vcpu, &host_os_sprs);
4005 	if (vcpu->arch.psscr != host_psscr)
4006 		mtspr(SPRN_PSSCR_PR, host_psscr);
4007 
4008 	return trap;
4009 }
4010 
4011 /*
4012  * Guest entry for POWER9 and later CPUs.
4013  */
4014 static int kvmhv_p9_guest_entry(struct kvm_vcpu *vcpu, u64 time_limit,
4015 			 unsigned long lpcr, u64 *tb)
4016 {
4017 	u64 next_timer;
4018 	int trap;
4019 
4020 	next_timer = timer_get_next_tb();
4021 	if (*tb >= next_timer)
4022 		return BOOK3S_INTERRUPT_HV_DECREMENTER;
4023 	if (next_timer < time_limit)
4024 		time_limit = next_timer;
4025 	else if (*tb >= time_limit) /* nested time limit */
4026 		return BOOK3S_INTERRUPT_NESTED_HV_DECREMENTER;
4027 
4028 	vcpu->arch.ceded = 0;
4029 
4030 	vcpu_vpa_increment_dispatch(vcpu);
4031 
4032 	if (kvmhv_on_pseries()) {
4033 		trap = kvmhv_vcpu_entry_p9_nested(vcpu, time_limit, lpcr, tb);
4034 
4035 		/* H_CEDE has to be handled now, not later */
4036 		if (trap == BOOK3S_INTERRUPT_SYSCALL && !vcpu->arch.nested &&
4037 		    kvmppc_get_gpr(vcpu, 3) == H_CEDE) {
4038 			kvmppc_cede(vcpu);
4039 			kvmppc_set_gpr(vcpu, 3, 0);
4040 			trap = 0;
4041 		}
4042 
4043 	} else {
4044 		struct kvm *kvm = vcpu->kvm;
4045 
4046 		kvmppc_xive_push_vcpu(vcpu);
4047 
4048 		__this_cpu_write(cpu_in_guest, kvm);
4049 		trap = kvmhv_vcpu_entry_p9(vcpu, time_limit, lpcr, tb);
4050 		__this_cpu_write(cpu_in_guest, NULL);
4051 
4052 		if (trap == BOOK3S_INTERRUPT_SYSCALL && !vcpu->arch.nested &&
4053 		    !(vcpu->arch.shregs.msr & MSR_PR)) {
4054 			unsigned long req = kvmppc_get_gpr(vcpu, 3);
4055 
4056 			/* H_CEDE has to be handled now, not later */
4057 			if (req == H_CEDE) {
4058 				kvmppc_cede(vcpu);
4059 				kvmppc_xive_rearm_escalation(vcpu); /* may un-cede */
4060 				kvmppc_set_gpr(vcpu, 3, 0);
4061 				trap = 0;
4062 
4063 			/* XICS hcalls must be handled before xive is pulled */
4064 			} else if (hcall_is_xics(req)) {
4065 				int ret;
4066 
4067 				ret = kvmppc_xive_xics_hcall(vcpu, req);
4068 				if (ret != H_TOO_HARD) {
4069 					kvmppc_set_gpr(vcpu, 3, ret);
4070 					trap = 0;
4071 				}
4072 			}
4073 		}
4074 		kvmppc_xive_pull_vcpu(vcpu);
4075 
4076 		if (kvm_is_radix(kvm))
4077 			vcpu->arch.slb_max = 0;
4078 	}
4079 
4080 	vcpu_vpa_increment_dispatch(vcpu);
4081 
4082 	return trap;
4083 }
4084 
4085 /*
4086  * Wait for some other vcpu thread to execute us, and
4087  * wake us up when we need to handle something in the host.
4088  */
4089 static void kvmppc_wait_for_exec(struct kvmppc_vcore *vc,
4090 				 struct kvm_vcpu *vcpu, int wait_state)
4091 {
4092 	DEFINE_WAIT(wait);
4093 
4094 	prepare_to_wait(&vcpu->arch.cpu_run, &wait, wait_state);
4095 	if (vcpu->arch.state == KVMPPC_VCPU_RUNNABLE) {
4096 		spin_unlock(&vc->lock);
4097 		schedule();
4098 		spin_lock(&vc->lock);
4099 	}
4100 	finish_wait(&vcpu->arch.cpu_run, &wait);
4101 }
4102 
4103 static void grow_halt_poll_ns(struct kvmppc_vcore *vc)
4104 {
4105 	if (!halt_poll_ns_grow)
4106 		return;
4107 
4108 	vc->halt_poll_ns *= halt_poll_ns_grow;
4109 	if (vc->halt_poll_ns < halt_poll_ns_grow_start)
4110 		vc->halt_poll_ns = halt_poll_ns_grow_start;
4111 }
4112 
4113 static void shrink_halt_poll_ns(struct kvmppc_vcore *vc)
4114 {
4115 	if (halt_poll_ns_shrink == 0)
4116 		vc->halt_poll_ns = 0;
4117 	else
4118 		vc->halt_poll_ns /= halt_poll_ns_shrink;
4119 }
4120 
4121 #ifdef CONFIG_KVM_XICS
4122 static inline bool xive_interrupt_pending(struct kvm_vcpu *vcpu)
4123 {
4124 	if (!xics_on_xive())
4125 		return false;
4126 	return vcpu->arch.irq_pending || vcpu->arch.xive_saved_state.pipr <
4127 		vcpu->arch.xive_saved_state.cppr;
4128 }
4129 #else
4130 static inline bool xive_interrupt_pending(struct kvm_vcpu *vcpu)
4131 {
4132 	return false;
4133 }
4134 #endif /* CONFIG_KVM_XICS */
4135 
4136 static bool kvmppc_vcpu_woken(struct kvm_vcpu *vcpu)
4137 {
4138 	if (vcpu->arch.pending_exceptions || vcpu->arch.prodded ||
4139 	    kvmppc_doorbell_pending(vcpu) || xive_interrupt_pending(vcpu))
4140 		return true;
4141 
4142 	return false;
4143 }
4144 
4145 static bool kvmppc_vcpu_check_block(struct kvm_vcpu *vcpu)
4146 {
4147 	if (!vcpu->arch.ceded || kvmppc_vcpu_woken(vcpu))
4148 		return true;
4149 	return false;
4150 }
4151 
4152 /*
4153  * Check to see if any of the runnable vcpus on the vcore have pending
4154  * exceptions or are no longer ceded
4155  */
4156 static int kvmppc_vcore_check_block(struct kvmppc_vcore *vc)
4157 {
4158 	struct kvm_vcpu *vcpu;
4159 	int i;
4160 
4161 	for_each_runnable_thread(i, vcpu, vc) {
4162 		if (kvmppc_vcpu_check_block(vcpu))
4163 			return 1;
4164 	}
4165 
4166 	return 0;
4167 }
4168 
4169 /*
4170  * All the vcpus in this vcore are idle, so wait for a decrementer
4171  * or external interrupt to one of the vcpus.  vc->lock is held.
4172  */
4173 static void kvmppc_vcore_blocked(struct kvmppc_vcore *vc)
4174 {
4175 	ktime_t cur, start_poll, start_wait;
4176 	int do_sleep = 1;
4177 	u64 block_ns;
4178 
4179 	WARN_ON_ONCE(cpu_has_feature(CPU_FTR_ARCH_300));
4180 
4181 	/* Poll for pending exceptions and ceded state */
4182 	cur = start_poll = ktime_get();
4183 	if (vc->halt_poll_ns) {
4184 		ktime_t stop = ktime_add_ns(start_poll, vc->halt_poll_ns);
4185 		++vc->runner->stat.generic.halt_attempted_poll;
4186 
4187 		vc->vcore_state = VCORE_POLLING;
4188 		spin_unlock(&vc->lock);
4189 
4190 		do {
4191 			if (kvmppc_vcore_check_block(vc)) {
4192 				do_sleep = 0;
4193 				break;
4194 			}
4195 			cur = ktime_get();
4196 		} while (kvm_vcpu_can_poll(cur, stop));
4197 
4198 		spin_lock(&vc->lock);
4199 		vc->vcore_state = VCORE_INACTIVE;
4200 
4201 		if (!do_sleep) {
4202 			++vc->runner->stat.generic.halt_successful_poll;
4203 			goto out;
4204 		}
4205 	}
4206 
4207 	prepare_to_rcuwait(&vc->wait);
4208 	set_current_state(TASK_INTERRUPTIBLE);
4209 	if (kvmppc_vcore_check_block(vc)) {
4210 		finish_rcuwait(&vc->wait);
4211 		do_sleep = 0;
4212 		/* If we polled, count this as a successful poll */
4213 		if (vc->halt_poll_ns)
4214 			++vc->runner->stat.generic.halt_successful_poll;
4215 		goto out;
4216 	}
4217 
4218 	start_wait = ktime_get();
4219 
4220 	vc->vcore_state = VCORE_SLEEPING;
4221 	trace_kvmppc_vcore_blocked(vc, 0);
4222 	spin_unlock(&vc->lock);
4223 	schedule();
4224 	finish_rcuwait(&vc->wait);
4225 	spin_lock(&vc->lock);
4226 	vc->vcore_state = VCORE_INACTIVE;
4227 	trace_kvmppc_vcore_blocked(vc, 1);
4228 	++vc->runner->stat.halt_successful_wait;
4229 
4230 	cur = ktime_get();
4231 
4232 out:
4233 	block_ns = ktime_to_ns(cur) - ktime_to_ns(start_poll);
4234 
4235 	/* Attribute wait time */
4236 	if (do_sleep) {
4237 		vc->runner->stat.generic.halt_wait_ns +=
4238 			ktime_to_ns(cur) - ktime_to_ns(start_wait);
4239 		KVM_STATS_LOG_HIST_UPDATE(
4240 				vc->runner->stat.generic.halt_wait_hist,
4241 				ktime_to_ns(cur) - ktime_to_ns(start_wait));
4242 		/* Attribute failed poll time */
4243 		if (vc->halt_poll_ns) {
4244 			vc->runner->stat.generic.halt_poll_fail_ns +=
4245 				ktime_to_ns(start_wait) -
4246 				ktime_to_ns(start_poll);
4247 			KVM_STATS_LOG_HIST_UPDATE(
4248 				vc->runner->stat.generic.halt_poll_fail_hist,
4249 				ktime_to_ns(start_wait) -
4250 				ktime_to_ns(start_poll));
4251 		}
4252 	} else {
4253 		/* Attribute successful poll time */
4254 		if (vc->halt_poll_ns) {
4255 			vc->runner->stat.generic.halt_poll_success_ns +=
4256 				ktime_to_ns(cur) -
4257 				ktime_to_ns(start_poll);
4258 			KVM_STATS_LOG_HIST_UPDATE(
4259 				vc->runner->stat.generic.halt_poll_success_hist,
4260 				ktime_to_ns(cur) - ktime_to_ns(start_poll));
4261 		}
4262 	}
4263 
4264 	/* Adjust poll time */
4265 	if (halt_poll_ns) {
4266 		if (block_ns <= vc->halt_poll_ns)
4267 			;
4268 		/* We slept and blocked for longer than the max halt time */
4269 		else if (vc->halt_poll_ns && block_ns > halt_poll_ns)
4270 			shrink_halt_poll_ns(vc);
4271 		/* We slept and our poll time is too small */
4272 		else if (vc->halt_poll_ns < halt_poll_ns &&
4273 				block_ns < halt_poll_ns)
4274 			grow_halt_poll_ns(vc);
4275 		if (vc->halt_poll_ns > halt_poll_ns)
4276 			vc->halt_poll_ns = halt_poll_ns;
4277 	} else
4278 		vc->halt_poll_ns = 0;
4279 
4280 	trace_kvmppc_vcore_wakeup(do_sleep, block_ns);
4281 }
4282 
4283 /*
4284  * This never fails for a radix guest, as none of the operations it does
4285  * for a radix guest can fail or have a way to report failure.
4286  */
4287 static int kvmhv_setup_mmu(struct kvm_vcpu *vcpu)
4288 {
4289 	int r = 0;
4290 	struct kvm *kvm = vcpu->kvm;
4291 
4292 	mutex_lock(&kvm->arch.mmu_setup_lock);
4293 	if (!kvm->arch.mmu_ready) {
4294 		if (!kvm_is_radix(kvm))
4295 			r = kvmppc_hv_setup_htab_rma(vcpu);
4296 		if (!r) {
4297 			if (cpu_has_feature(CPU_FTR_ARCH_300))
4298 				kvmppc_setup_partition_table(kvm);
4299 			kvm->arch.mmu_ready = 1;
4300 		}
4301 	}
4302 	mutex_unlock(&kvm->arch.mmu_setup_lock);
4303 	return r;
4304 }
4305 
4306 static int kvmppc_run_vcpu(struct kvm_vcpu *vcpu)
4307 {
4308 	struct kvm_run *run = vcpu->run;
4309 	int n_ceded, i, r;
4310 	struct kvmppc_vcore *vc;
4311 	struct kvm_vcpu *v;
4312 
4313 	trace_kvmppc_run_vcpu_enter(vcpu);
4314 
4315 	run->exit_reason = 0;
4316 	vcpu->arch.ret = RESUME_GUEST;
4317 	vcpu->arch.trap = 0;
4318 	kvmppc_update_vpas(vcpu);
4319 
4320 	/*
4321 	 * Synchronize with other threads in this virtual core
4322 	 */
4323 	vc = vcpu->arch.vcore;
4324 	spin_lock(&vc->lock);
4325 	vcpu->arch.ceded = 0;
4326 	vcpu->arch.run_task = current;
4327 	vcpu->arch.stolen_logged = vcore_stolen_time(vc, mftb());
4328 	vcpu->arch.state = KVMPPC_VCPU_RUNNABLE;
4329 	vcpu->arch.busy_preempt = TB_NIL;
4330 	WRITE_ONCE(vc->runnable_threads[vcpu->arch.ptid], vcpu);
4331 	++vc->n_runnable;
4332 
4333 	/*
4334 	 * This happens the first time this is called for a vcpu.
4335 	 * If the vcore is already running, we may be able to start
4336 	 * this thread straight away and have it join in.
4337 	 */
4338 	if (!signal_pending(current)) {
4339 		if ((vc->vcore_state == VCORE_PIGGYBACK ||
4340 		     vc->vcore_state == VCORE_RUNNING) &&
4341 			   !VCORE_IS_EXITING(vc)) {
4342 			kvmppc_create_dtl_entry(vcpu, vc);
4343 			kvmppc_start_thread(vcpu, vc);
4344 			trace_kvm_guest_enter(vcpu);
4345 		} else if (vc->vcore_state == VCORE_SLEEPING) {
4346 		        rcuwait_wake_up(&vc->wait);
4347 		}
4348 
4349 	}
4350 
4351 	while (vcpu->arch.state == KVMPPC_VCPU_RUNNABLE &&
4352 	       !signal_pending(current)) {
4353 		/* See if the MMU is ready to go */
4354 		if (!vcpu->kvm->arch.mmu_ready) {
4355 			spin_unlock(&vc->lock);
4356 			r = kvmhv_setup_mmu(vcpu);
4357 			spin_lock(&vc->lock);
4358 			if (r) {
4359 				run->exit_reason = KVM_EXIT_FAIL_ENTRY;
4360 				run->fail_entry.
4361 					hardware_entry_failure_reason = 0;
4362 				vcpu->arch.ret = r;
4363 				break;
4364 			}
4365 		}
4366 
4367 		if (vc->vcore_state == VCORE_PREEMPT && vc->runner == NULL)
4368 			kvmppc_vcore_end_preempt(vc);
4369 
4370 		if (vc->vcore_state != VCORE_INACTIVE) {
4371 			kvmppc_wait_for_exec(vc, vcpu, TASK_INTERRUPTIBLE);
4372 			continue;
4373 		}
4374 		for_each_runnable_thread(i, v, vc) {
4375 			kvmppc_core_prepare_to_enter(v);
4376 			if (signal_pending(v->arch.run_task)) {
4377 				kvmppc_remove_runnable(vc, v, mftb());
4378 				v->stat.signal_exits++;
4379 				v->run->exit_reason = KVM_EXIT_INTR;
4380 				v->arch.ret = -EINTR;
4381 				wake_up(&v->arch.cpu_run);
4382 			}
4383 		}
4384 		if (!vc->n_runnable || vcpu->arch.state != KVMPPC_VCPU_RUNNABLE)
4385 			break;
4386 		n_ceded = 0;
4387 		for_each_runnable_thread(i, v, vc) {
4388 			if (!kvmppc_vcpu_woken(v))
4389 				n_ceded += v->arch.ceded;
4390 			else
4391 				v->arch.ceded = 0;
4392 		}
4393 		vc->runner = vcpu;
4394 		if (n_ceded == vc->n_runnable) {
4395 			kvmppc_vcore_blocked(vc);
4396 		} else if (need_resched()) {
4397 			kvmppc_vcore_preempt(vc);
4398 			/* Let something else run */
4399 			cond_resched_lock(&vc->lock);
4400 			if (vc->vcore_state == VCORE_PREEMPT)
4401 				kvmppc_vcore_end_preempt(vc);
4402 		} else {
4403 			kvmppc_run_core(vc);
4404 		}
4405 		vc->runner = NULL;
4406 	}
4407 
4408 	while (vcpu->arch.state == KVMPPC_VCPU_RUNNABLE &&
4409 	       (vc->vcore_state == VCORE_RUNNING ||
4410 		vc->vcore_state == VCORE_EXITING ||
4411 		vc->vcore_state == VCORE_PIGGYBACK))
4412 		kvmppc_wait_for_exec(vc, vcpu, TASK_UNINTERRUPTIBLE);
4413 
4414 	if (vc->vcore_state == VCORE_PREEMPT && vc->runner == NULL)
4415 		kvmppc_vcore_end_preempt(vc);
4416 
4417 	if (vcpu->arch.state == KVMPPC_VCPU_RUNNABLE) {
4418 		kvmppc_remove_runnable(vc, vcpu, mftb());
4419 		vcpu->stat.signal_exits++;
4420 		run->exit_reason = KVM_EXIT_INTR;
4421 		vcpu->arch.ret = -EINTR;
4422 	}
4423 
4424 	if (vc->n_runnable && vc->vcore_state == VCORE_INACTIVE) {
4425 		/* Wake up some vcpu to run the core */
4426 		i = -1;
4427 		v = next_runnable_thread(vc, &i);
4428 		wake_up(&v->arch.cpu_run);
4429 	}
4430 
4431 	trace_kvmppc_run_vcpu_exit(vcpu);
4432 	spin_unlock(&vc->lock);
4433 	return vcpu->arch.ret;
4434 }
4435 
4436 int kvmhv_run_single_vcpu(struct kvm_vcpu *vcpu, u64 time_limit,
4437 			  unsigned long lpcr)
4438 {
4439 	struct rcuwait *wait = kvm_arch_vcpu_get_wait(vcpu);
4440 	struct kvm_run *run = vcpu->run;
4441 	int trap, r, pcpu;
4442 	int srcu_idx;
4443 	struct kvmppc_vcore *vc;
4444 	struct kvm *kvm = vcpu->kvm;
4445 	struct kvm_nested_guest *nested = vcpu->arch.nested;
4446 	unsigned long flags;
4447 	u64 tb;
4448 
4449 	trace_kvmppc_run_vcpu_enter(vcpu);
4450 
4451 	run->exit_reason = 0;
4452 	vcpu->arch.ret = RESUME_GUEST;
4453 	vcpu->arch.trap = 0;
4454 
4455 	vc = vcpu->arch.vcore;
4456 	vcpu->arch.ceded = 0;
4457 	vcpu->arch.run_task = current;
4458 	vcpu->arch.state = KVMPPC_VCPU_RUNNABLE;
4459 	vcpu->arch.last_inst = KVM_INST_FETCH_FAILED;
4460 
4461 	/* See if the MMU is ready to go */
4462 	if (unlikely(!kvm->arch.mmu_ready)) {
4463 		r = kvmhv_setup_mmu(vcpu);
4464 		if (r) {
4465 			run->exit_reason = KVM_EXIT_FAIL_ENTRY;
4466 			run->fail_entry.hardware_entry_failure_reason = 0;
4467 			vcpu->arch.ret = r;
4468 			return r;
4469 		}
4470 	}
4471 
4472 	if (need_resched())
4473 		cond_resched();
4474 
4475 	kvmppc_update_vpas(vcpu);
4476 
4477 	preempt_disable();
4478 	pcpu = smp_processor_id();
4479 	if (kvm_is_radix(kvm))
4480 		kvmppc_prepare_radix_vcpu(vcpu, pcpu);
4481 
4482 	/* flags save not required, but irq_pmu has no disable/enable API */
4483 	powerpc_local_irq_pmu_save(flags);
4484 
4485 	if (signal_pending(current))
4486 		goto sigpend;
4487 	if (need_resched() || !kvm->arch.mmu_ready)
4488 		goto out;
4489 
4490 	if (!nested) {
4491 		kvmppc_core_prepare_to_enter(vcpu);
4492 		if (test_bit(BOOK3S_IRQPRIO_EXTERNAL,
4493 			     &vcpu->arch.pending_exceptions))
4494 			lpcr |= LPCR_MER;
4495 	} else if (vcpu->arch.pending_exceptions ||
4496 		   vcpu->arch.doorbell_request ||
4497 		   xive_interrupt_pending(vcpu)) {
4498 		vcpu->arch.ret = RESUME_HOST;
4499 		goto out;
4500 	}
4501 
4502 	if (vcpu->arch.timer_running) {
4503 		hrtimer_try_to_cancel(&vcpu->arch.dec_timer);
4504 		vcpu->arch.timer_running = 0;
4505 	}
4506 
4507 	tb = mftb();
4508 
4509 	vcpu->cpu = pcpu;
4510 	vcpu->arch.thread_cpu = pcpu;
4511 	vc->pcpu = pcpu;
4512 	local_paca->kvm_hstate.kvm_vcpu = vcpu;
4513 	local_paca->kvm_hstate.ptid = 0;
4514 	local_paca->kvm_hstate.fake_suspend = 0;
4515 
4516 	__kvmppc_create_dtl_entry(vcpu, pcpu, tb + vc->tb_offset, 0);
4517 
4518 	trace_kvm_guest_enter(vcpu);
4519 
4520 	guest_enter_irqoff();
4521 
4522 	srcu_idx = srcu_read_lock(&kvm->srcu);
4523 
4524 	this_cpu_disable_ftrace();
4525 
4526 	/* Tell lockdep that we're about to enable interrupts */
4527 	trace_hardirqs_on();
4528 
4529 	trap = kvmhv_p9_guest_entry(vcpu, time_limit, lpcr, &tb);
4530 	vcpu->arch.trap = trap;
4531 
4532 	trace_hardirqs_off();
4533 
4534 	this_cpu_enable_ftrace();
4535 
4536 	srcu_read_unlock(&kvm->srcu, srcu_idx);
4537 
4538 	set_irq_happened(trap);
4539 
4540 	context_tracking_guest_exit();
4541 	if (!vtime_accounting_enabled_this_cpu()) {
4542 		local_irq_enable();
4543 		/*
4544 		 * Service IRQs here before vtime_account_guest_exit() so any
4545 		 * ticks that occurred while running the guest are accounted to
4546 		 * the guest. If vtime accounting is enabled, accounting uses
4547 		 * TB rather than ticks, so it can be done without enabling
4548 		 * interrupts here, which has the problem that it accounts
4549 		 * interrupt processing overhead to the host.
4550 		 */
4551 		local_irq_disable();
4552 	}
4553 	vtime_account_guest_exit();
4554 
4555 	vcpu->cpu = -1;
4556 	vcpu->arch.thread_cpu = -1;
4557 
4558 	powerpc_local_irq_pmu_restore(flags);
4559 
4560 	preempt_enable();
4561 
4562 	/*
4563 	 * cancel pending decrementer exception if DEC is now positive, or if
4564 	 * entering a nested guest in which case the decrementer is now owned
4565 	 * by L2 and the L1 decrementer is provided in hdec_expires
4566 	 */
4567 	if (kvmppc_core_pending_dec(vcpu) &&
4568 			((tb < kvmppc_dec_expires_host_tb(vcpu)) ||
4569 			 (trap == BOOK3S_INTERRUPT_SYSCALL &&
4570 			  kvmppc_get_gpr(vcpu, 3) == H_ENTER_NESTED)))
4571 		kvmppc_core_dequeue_dec(vcpu);
4572 
4573 	trace_kvm_guest_exit(vcpu);
4574 	r = RESUME_GUEST;
4575 	if (trap) {
4576 		if (!nested)
4577 			r = kvmppc_handle_exit_hv(vcpu, current);
4578 		else
4579 			r = kvmppc_handle_nested_exit(vcpu);
4580 	}
4581 	vcpu->arch.ret = r;
4582 
4583 	if (is_kvmppc_resume_guest(r) && !kvmppc_vcpu_check_block(vcpu)) {
4584 		kvmppc_set_timer(vcpu);
4585 
4586 		prepare_to_rcuwait(wait);
4587 		for (;;) {
4588 			set_current_state(TASK_INTERRUPTIBLE);
4589 			if (signal_pending(current)) {
4590 				vcpu->stat.signal_exits++;
4591 				run->exit_reason = KVM_EXIT_INTR;
4592 				vcpu->arch.ret = -EINTR;
4593 				break;
4594 			}
4595 
4596 			if (kvmppc_vcpu_check_block(vcpu))
4597 				break;
4598 
4599 			trace_kvmppc_vcore_blocked(vc, 0);
4600 			schedule();
4601 			trace_kvmppc_vcore_blocked(vc, 1);
4602 		}
4603 		finish_rcuwait(wait);
4604 	}
4605 	vcpu->arch.ceded = 0;
4606 
4607  done:
4608 	trace_kvmppc_run_vcpu_exit(vcpu);
4609 
4610 	return vcpu->arch.ret;
4611 
4612  sigpend:
4613 	vcpu->stat.signal_exits++;
4614 	run->exit_reason = KVM_EXIT_INTR;
4615 	vcpu->arch.ret = -EINTR;
4616  out:
4617 	powerpc_local_irq_pmu_restore(flags);
4618 	preempt_enable();
4619 	goto done;
4620 }
4621 
4622 static int kvmppc_vcpu_run_hv(struct kvm_vcpu *vcpu)
4623 {
4624 	struct kvm_run *run = vcpu->run;
4625 	int r;
4626 	int srcu_idx;
4627 	struct kvm *kvm;
4628 	unsigned long msr;
4629 
4630 	if (!vcpu->arch.sane) {
4631 		run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
4632 		return -EINVAL;
4633 	}
4634 
4635 	/* No need to go into the guest when all we'll do is come back out */
4636 	if (signal_pending(current)) {
4637 		run->exit_reason = KVM_EXIT_INTR;
4638 		return -EINTR;
4639 	}
4640 
4641 #ifdef CONFIG_PPC_TRANSACTIONAL_MEM
4642 	/*
4643 	 * Don't allow entry with a suspended transaction, because
4644 	 * the guest entry/exit code will lose it.
4645 	 */
4646 	if (cpu_has_feature(CPU_FTR_TM) && current->thread.regs &&
4647 	    (current->thread.regs->msr & MSR_TM)) {
4648 		if (MSR_TM_ACTIVE(current->thread.regs->msr)) {
4649 			run->exit_reason = KVM_EXIT_FAIL_ENTRY;
4650 			run->fail_entry.hardware_entry_failure_reason = 0;
4651 			return -EINVAL;
4652 		}
4653 	}
4654 #endif
4655 
4656 	/*
4657 	 * Force online to 1 for the sake of old userspace which doesn't
4658 	 * set it.
4659 	 */
4660 	if (!vcpu->arch.online) {
4661 		atomic_inc(&vcpu->arch.vcore->online_count);
4662 		vcpu->arch.online = 1;
4663 	}
4664 
4665 	kvmppc_core_prepare_to_enter(vcpu);
4666 
4667 	kvm = vcpu->kvm;
4668 	atomic_inc(&kvm->arch.vcpus_running);
4669 	/* Order vcpus_running vs. mmu_ready, see kvmppc_alloc_reset_hpt */
4670 	smp_mb();
4671 
4672 	msr = 0;
4673 	if (IS_ENABLED(CONFIG_PPC_FPU))
4674 		msr |= MSR_FP;
4675 	if (cpu_has_feature(CPU_FTR_ALTIVEC))
4676 		msr |= MSR_VEC;
4677 	if (cpu_has_feature(CPU_FTR_VSX))
4678 		msr |= MSR_VSX;
4679 	if ((cpu_has_feature(CPU_FTR_TM) ||
4680 	    cpu_has_feature(CPU_FTR_P9_TM_HV_ASSIST)) &&
4681 			(vcpu->arch.hfscr & HFSCR_TM))
4682 		msr |= MSR_TM;
4683 	msr = msr_check_and_set(msr);
4684 
4685 	kvmppc_save_user_regs();
4686 
4687 	kvmppc_save_current_sprs();
4688 
4689 	if (!cpu_has_feature(CPU_FTR_ARCH_300))
4690 		vcpu->arch.waitp = &vcpu->arch.vcore->wait;
4691 	vcpu->arch.pgdir = kvm->mm->pgd;
4692 	vcpu->arch.state = KVMPPC_VCPU_BUSY_IN_HOST;
4693 
4694 	do {
4695 		if (cpu_has_feature(CPU_FTR_ARCH_300))
4696 			r = kvmhv_run_single_vcpu(vcpu, ~(u64)0,
4697 						  vcpu->arch.vcore->lpcr);
4698 		else
4699 			r = kvmppc_run_vcpu(vcpu);
4700 
4701 		if (run->exit_reason == KVM_EXIT_PAPR_HCALL) {
4702 			if (WARN_ON_ONCE(vcpu->arch.shregs.msr & MSR_PR)) {
4703 				/*
4704 				 * These should have been caught reflected
4705 				 * into the guest by now. Final sanity check:
4706 				 * don't allow userspace to execute hcalls in
4707 				 * the hypervisor.
4708 				 */
4709 				r = RESUME_GUEST;
4710 				continue;
4711 			}
4712 			trace_kvm_hcall_enter(vcpu);
4713 			r = kvmppc_pseries_do_hcall(vcpu);
4714 			trace_kvm_hcall_exit(vcpu, r);
4715 			kvmppc_core_prepare_to_enter(vcpu);
4716 		} else if (r == RESUME_PAGE_FAULT) {
4717 			srcu_idx = srcu_read_lock(&kvm->srcu);
4718 			r = kvmppc_book3s_hv_page_fault(vcpu,
4719 				vcpu->arch.fault_dar, vcpu->arch.fault_dsisr);
4720 			srcu_read_unlock(&kvm->srcu, srcu_idx);
4721 		} else if (r == RESUME_PASSTHROUGH) {
4722 			if (WARN_ON(xics_on_xive()))
4723 				r = H_SUCCESS;
4724 			else
4725 				r = kvmppc_xics_rm_complete(vcpu, 0);
4726 		}
4727 	} while (is_kvmppc_resume_guest(r));
4728 
4729 	vcpu->arch.state = KVMPPC_VCPU_NOTREADY;
4730 	atomic_dec(&kvm->arch.vcpus_running);
4731 
4732 	srr_regs_clobbered();
4733 
4734 	return r;
4735 }
4736 
4737 static void kvmppc_add_seg_page_size(struct kvm_ppc_one_seg_page_size **sps,
4738 				     int shift, int sllp)
4739 {
4740 	(*sps)->page_shift = shift;
4741 	(*sps)->slb_enc = sllp;
4742 	(*sps)->enc[0].page_shift = shift;
4743 	(*sps)->enc[0].pte_enc = kvmppc_pgsize_lp_encoding(shift, shift);
4744 	/*
4745 	 * Add 16MB MPSS support (may get filtered out by userspace)
4746 	 */
4747 	if (shift != 24) {
4748 		int penc = kvmppc_pgsize_lp_encoding(shift, 24);
4749 		if (penc != -1) {
4750 			(*sps)->enc[1].page_shift = 24;
4751 			(*sps)->enc[1].pte_enc = penc;
4752 		}
4753 	}
4754 	(*sps)++;
4755 }
4756 
4757 static int kvm_vm_ioctl_get_smmu_info_hv(struct kvm *kvm,
4758 					 struct kvm_ppc_smmu_info *info)
4759 {
4760 	struct kvm_ppc_one_seg_page_size *sps;
4761 
4762 	/*
4763 	 * POWER7, POWER8 and POWER9 all support 32 storage keys for data.
4764 	 * POWER7 doesn't support keys for instruction accesses,
4765 	 * POWER8 and POWER9 do.
4766 	 */
4767 	info->data_keys = 32;
4768 	info->instr_keys = cpu_has_feature(CPU_FTR_ARCH_207S) ? 32 : 0;
4769 
4770 	/* POWER7, 8 and 9 all have 1T segments and 32-entry SLB */
4771 	info->flags = KVM_PPC_PAGE_SIZES_REAL | KVM_PPC_1T_SEGMENTS;
4772 	info->slb_size = 32;
4773 
4774 	/* We only support these sizes for now, and no muti-size segments */
4775 	sps = &info->sps[0];
4776 	kvmppc_add_seg_page_size(&sps, 12, 0);
4777 	kvmppc_add_seg_page_size(&sps, 16, SLB_VSID_L | SLB_VSID_LP_01);
4778 	kvmppc_add_seg_page_size(&sps, 24, SLB_VSID_L);
4779 
4780 	/* If running as a nested hypervisor, we don't support HPT guests */
4781 	if (kvmhv_on_pseries())
4782 		info->flags |= KVM_PPC_NO_HASH;
4783 
4784 	return 0;
4785 }
4786 
4787 /*
4788  * Get (and clear) the dirty memory log for a memory slot.
4789  */
4790 static int kvm_vm_ioctl_get_dirty_log_hv(struct kvm *kvm,
4791 					 struct kvm_dirty_log *log)
4792 {
4793 	struct kvm_memslots *slots;
4794 	struct kvm_memory_slot *memslot;
4795 	int r;
4796 	unsigned long n, i;
4797 	unsigned long *buf, *p;
4798 	struct kvm_vcpu *vcpu;
4799 
4800 	mutex_lock(&kvm->slots_lock);
4801 
4802 	r = -EINVAL;
4803 	if (log->slot >= KVM_USER_MEM_SLOTS)
4804 		goto out;
4805 
4806 	slots = kvm_memslots(kvm);
4807 	memslot = id_to_memslot(slots, log->slot);
4808 	r = -ENOENT;
4809 	if (!memslot || !memslot->dirty_bitmap)
4810 		goto out;
4811 
4812 	/*
4813 	 * Use second half of bitmap area because both HPT and radix
4814 	 * accumulate bits in the first half.
4815 	 */
4816 	n = kvm_dirty_bitmap_bytes(memslot);
4817 	buf = memslot->dirty_bitmap + n / sizeof(long);
4818 	memset(buf, 0, n);
4819 
4820 	if (kvm_is_radix(kvm))
4821 		r = kvmppc_hv_get_dirty_log_radix(kvm, memslot, buf);
4822 	else
4823 		r = kvmppc_hv_get_dirty_log_hpt(kvm, memslot, buf);
4824 	if (r)
4825 		goto out;
4826 
4827 	/*
4828 	 * We accumulate dirty bits in the first half of the
4829 	 * memslot's dirty_bitmap area, for when pages are paged
4830 	 * out or modified by the host directly.  Pick up these
4831 	 * bits and add them to the map.
4832 	 */
4833 	p = memslot->dirty_bitmap;
4834 	for (i = 0; i < n / sizeof(long); ++i)
4835 		buf[i] |= xchg(&p[i], 0);
4836 
4837 	/* Harvest dirty bits from VPA and DTL updates */
4838 	/* Note: we never modify the SLB shadow buffer areas */
4839 	kvm_for_each_vcpu(i, vcpu, kvm) {
4840 		spin_lock(&vcpu->arch.vpa_update_lock);
4841 		kvmppc_harvest_vpa_dirty(&vcpu->arch.vpa, memslot, buf);
4842 		kvmppc_harvest_vpa_dirty(&vcpu->arch.dtl, memslot, buf);
4843 		spin_unlock(&vcpu->arch.vpa_update_lock);
4844 	}
4845 
4846 	r = -EFAULT;
4847 	if (copy_to_user(log->dirty_bitmap, buf, n))
4848 		goto out;
4849 
4850 	r = 0;
4851 out:
4852 	mutex_unlock(&kvm->slots_lock);
4853 	return r;
4854 }
4855 
4856 static void kvmppc_core_free_memslot_hv(struct kvm_memory_slot *slot)
4857 {
4858 	vfree(slot->arch.rmap);
4859 	slot->arch.rmap = NULL;
4860 }
4861 
4862 static int kvmppc_core_prepare_memory_region_hv(struct kvm *kvm,
4863 				const struct kvm_memory_slot *old,
4864 				struct kvm_memory_slot *new,
4865 				enum kvm_mr_change change)
4866 {
4867 	if (change == KVM_MR_CREATE) {
4868 		unsigned long size = array_size(new->npages, sizeof(*new->arch.rmap));
4869 
4870 		if ((size >> PAGE_SHIFT) > totalram_pages())
4871 			return -ENOMEM;
4872 
4873 		new->arch.rmap = vzalloc(size);
4874 		if (!new->arch.rmap)
4875 			return -ENOMEM;
4876 	} else if (change != KVM_MR_DELETE) {
4877 		new->arch.rmap = old->arch.rmap;
4878 	}
4879 
4880 	return 0;
4881 }
4882 
4883 static void kvmppc_core_commit_memory_region_hv(struct kvm *kvm,
4884 				struct kvm_memory_slot *old,
4885 				const struct kvm_memory_slot *new,
4886 				enum kvm_mr_change change)
4887 {
4888 	/*
4889 	 * If we are creating or modifying a memslot, it might make
4890 	 * some address that was previously cached as emulated
4891 	 * MMIO be no longer emulated MMIO, so invalidate
4892 	 * all the caches of emulated MMIO translations.
4893 	 */
4894 	if (change != KVM_MR_DELETE)
4895 		atomic64_inc(&kvm->arch.mmio_update);
4896 
4897 	/*
4898 	 * For change == KVM_MR_MOVE or KVM_MR_DELETE, higher levels
4899 	 * have already called kvm_arch_flush_shadow_memslot() to
4900 	 * flush shadow mappings.  For KVM_MR_CREATE we have no
4901 	 * previous mappings.  So the only case to handle is
4902 	 * KVM_MR_FLAGS_ONLY when the KVM_MEM_LOG_DIRTY_PAGES bit
4903 	 * has been changed.
4904 	 * For radix guests, we flush on setting KVM_MEM_LOG_DIRTY_PAGES
4905 	 * to get rid of any THP PTEs in the partition-scoped page tables
4906 	 * so we can track dirtiness at the page level; we flush when
4907 	 * clearing KVM_MEM_LOG_DIRTY_PAGES so that we can go back to
4908 	 * using THP PTEs.
4909 	 */
4910 	if (change == KVM_MR_FLAGS_ONLY && kvm_is_radix(kvm) &&
4911 	    ((new->flags ^ old->flags) & KVM_MEM_LOG_DIRTY_PAGES))
4912 		kvmppc_radix_flush_memslot(kvm, old);
4913 	/*
4914 	 * If UV hasn't yet called H_SVM_INIT_START, don't register memslots.
4915 	 */
4916 	if (!kvm->arch.secure_guest)
4917 		return;
4918 
4919 	switch (change) {
4920 	case KVM_MR_CREATE:
4921 		/*
4922 		 * @TODO kvmppc_uvmem_memslot_create() can fail and
4923 		 * return error. Fix this.
4924 		 */
4925 		kvmppc_uvmem_memslot_create(kvm, new);
4926 		break;
4927 	case KVM_MR_DELETE:
4928 		kvmppc_uvmem_memslot_delete(kvm, old);
4929 		break;
4930 	default:
4931 		/* TODO: Handle KVM_MR_MOVE */
4932 		break;
4933 	}
4934 }
4935 
4936 /*
4937  * Update LPCR values in kvm->arch and in vcores.
4938  * Caller must hold kvm->arch.mmu_setup_lock (for mutual exclusion
4939  * of kvm->arch.lpcr update).
4940  */
4941 void kvmppc_update_lpcr(struct kvm *kvm, unsigned long lpcr, unsigned long mask)
4942 {
4943 	long int i;
4944 	u32 cores_done = 0;
4945 
4946 	if ((kvm->arch.lpcr & mask) == lpcr)
4947 		return;
4948 
4949 	kvm->arch.lpcr = (kvm->arch.lpcr & ~mask) | lpcr;
4950 
4951 	for (i = 0; i < KVM_MAX_VCORES; ++i) {
4952 		struct kvmppc_vcore *vc = kvm->arch.vcores[i];
4953 		if (!vc)
4954 			continue;
4955 
4956 		spin_lock(&vc->lock);
4957 		vc->lpcr = (vc->lpcr & ~mask) | lpcr;
4958 		verify_lpcr(kvm, vc->lpcr);
4959 		spin_unlock(&vc->lock);
4960 		if (++cores_done >= kvm->arch.online_vcores)
4961 			break;
4962 	}
4963 }
4964 
4965 void kvmppc_setup_partition_table(struct kvm *kvm)
4966 {
4967 	unsigned long dw0, dw1;
4968 
4969 	if (!kvm_is_radix(kvm)) {
4970 		/* PS field - page size for VRMA */
4971 		dw0 = ((kvm->arch.vrma_slb_v & SLB_VSID_L) >> 1) |
4972 			((kvm->arch.vrma_slb_v & SLB_VSID_LP) << 1);
4973 		/* HTABSIZE and HTABORG fields */
4974 		dw0 |= kvm->arch.sdr1;
4975 
4976 		/* Second dword as set by userspace */
4977 		dw1 = kvm->arch.process_table;
4978 	} else {
4979 		dw0 = PATB_HR | radix__get_tree_size() |
4980 			__pa(kvm->arch.pgtable) | RADIX_PGD_INDEX_SIZE;
4981 		dw1 = PATB_GR | kvm->arch.process_table;
4982 	}
4983 	kvmhv_set_ptbl_entry(kvm->arch.lpid, dw0, dw1);
4984 }
4985 
4986 /*
4987  * Set up HPT (hashed page table) and RMA (real-mode area).
4988  * Must be called with kvm->arch.mmu_setup_lock held.
4989  */
4990 static int kvmppc_hv_setup_htab_rma(struct kvm_vcpu *vcpu)
4991 {
4992 	int err = 0;
4993 	struct kvm *kvm = vcpu->kvm;
4994 	unsigned long hva;
4995 	struct kvm_memory_slot *memslot;
4996 	struct vm_area_struct *vma;
4997 	unsigned long lpcr = 0, senc;
4998 	unsigned long psize, porder;
4999 	int srcu_idx;
5000 
5001 	/* Allocate hashed page table (if not done already) and reset it */
5002 	if (!kvm->arch.hpt.virt) {
5003 		int order = KVM_DEFAULT_HPT_ORDER;
5004 		struct kvm_hpt_info info;
5005 
5006 		err = kvmppc_allocate_hpt(&info, order);
5007 		/* If we get here, it means userspace didn't specify a
5008 		 * size explicitly.  So, try successively smaller
5009 		 * sizes if the default failed. */
5010 		while ((err == -ENOMEM) && --order >= PPC_MIN_HPT_ORDER)
5011 			err  = kvmppc_allocate_hpt(&info, order);
5012 
5013 		if (err < 0) {
5014 			pr_err("KVM: Couldn't alloc HPT\n");
5015 			goto out;
5016 		}
5017 
5018 		kvmppc_set_hpt(kvm, &info);
5019 	}
5020 
5021 	/* Look up the memslot for guest physical address 0 */
5022 	srcu_idx = srcu_read_lock(&kvm->srcu);
5023 	memslot = gfn_to_memslot(kvm, 0);
5024 
5025 	/* We must have some memory at 0 by now */
5026 	err = -EINVAL;
5027 	if (!memslot || (memslot->flags & KVM_MEMSLOT_INVALID))
5028 		goto out_srcu;
5029 
5030 	/* Look up the VMA for the start of this memory slot */
5031 	hva = memslot->userspace_addr;
5032 	mmap_read_lock(kvm->mm);
5033 	vma = vma_lookup(kvm->mm, hva);
5034 	if (!vma || (vma->vm_flags & VM_IO))
5035 		goto up_out;
5036 
5037 	psize = vma_kernel_pagesize(vma);
5038 
5039 	mmap_read_unlock(kvm->mm);
5040 
5041 	/* We can handle 4k, 64k or 16M pages in the VRMA */
5042 	if (psize >= 0x1000000)
5043 		psize = 0x1000000;
5044 	else if (psize >= 0x10000)
5045 		psize = 0x10000;
5046 	else
5047 		psize = 0x1000;
5048 	porder = __ilog2(psize);
5049 
5050 	senc = slb_pgsize_encoding(psize);
5051 	kvm->arch.vrma_slb_v = senc | SLB_VSID_B_1T |
5052 		(VRMA_VSID << SLB_VSID_SHIFT_1T);
5053 	/* Create HPTEs in the hash page table for the VRMA */
5054 	kvmppc_map_vrma(vcpu, memslot, porder);
5055 
5056 	/* Update VRMASD field in the LPCR */
5057 	if (!cpu_has_feature(CPU_FTR_ARCH_300)) {
5058 		/* the -4 is to account for senc values starting at 0x10 */
5059 		lpcr = senc << (LPCR_VRMASD_SH - 4);
5060 		kvmppc_update_lpcr(kvm, lpcr, LPCR_VRMASD);
5061 	}
5062 
5063 	/* Order updates to kvm->arch.lpcr etc. vs. mmu_ready */
5064 	smp_wmb();
5065 	err = 0;
5066  out_srcu:
5067 	srcu_read_unlock(&kvm->srcu, srcu_idx);
5068  out:
5069 	return err;
5070 
5071  up_out:
5072 	mmap_read_unlock(kvm->mm);
5073 	goto out_srcu;
5074 }
5075 
5076 /*
5077  * Must be called with kvm->arch.mmu_setup_lock held and
5078  * mmu_ready = 0 and no vcpus running.
5079  */
5080 int kvmppc_switch_mmu_to_hpt(struct kvm *kvm)
5081 {
5082 	unsigned long lpcr, lpcr_mask;
5083 
5084 	if (nesting_enabled(kvm))
5085 		kvmhv_release_all_nested(kvm);
5086 	kvmppc_rmap_reset(kvm);
5087 	kvm->arch.process_table = 0;
5088 	/* Mutual exclusion with kvm_unmap_gfn_range etc. */
5089 	spin_lock(&kvm->mmu_lock);
5090 	kvm->arch.radix = 0;
5091 	spin_unlock(&kvm->mmu_lock);
5092 	kvmppc_free_radix(kvm);
5093 
5094 	lpcr = LPCR_VPM1;
5095 	lpcr_mask = LPCR_VPM1 | LPCR_UPRT | LPCR_GTSE | LPCR_HR;
5096 	if (cpu_has_feature(CPU_FTR_ARCH_31))
5097 		lpcr_mask |= LPCR_HAIL;
5098 	kvmppc_update_lpcr(kvm, lpcr, lpcr_mask);
5099 
5100 	return 0;
5101 }
5102 
5103 /*
5104  * Must be called with kvm->arch.mmu_setup_lock held and
5105  * mmu_ready = 0 and no vcpus running.
5106  */
5107 int kvmppc_switch_mmu_to_radix(struct kvm *kvm)
5108 {
5109 	unsigned long lpcr, lpcr_mask;
5110 	int err;
5111 
5112 	err = kvmppc_init_vm_radix(kvm);
5113 	if (err)
5114 		return err;
5115 	kvmppc_rmap_reset(kvm);
5116 	/* Mutual exclusion with kvm_unmap_gfn_range etc. */
5117 	spin_lock(&kvm->mmu_lock);
5118 	kvm->arch.radix = 1;
5119 	spin_unlock(&kvm->mmu_lock);
5120 	kvmppc_free_hpt(&kvm->arch.hpt);
5121 
5122 	lpcr = LPCR_UPRT | LPCR_GTSE | LPCR_HR;
5123 	lpcr_mask = LPCR_VPM1 | LPCR_UPRT | LPCR_GTSE | LPCR_HR;
5124 	if (cpu_has_feature(CPU_FTR_ARCH_31)) {
5125 		lpcr_mask |= LPCR_HAIL;
5126 		if (cpu_has_feature(CPU_FTR_HVMODE) &&
5127 				(kvm->arch.host_lpcr & LPCR_HAIL))
5128 			lpcr |= LPCR_HAIL;
5129 	}
5130 	kvmppc_update_lpcr(kvm, lpcr, lpcr_mask);
5131 
5132 	return 0;
5133 }
5134 
5135 #ifdef CONFIG_KVM_XICS
5136 /*
5137  * Allocate a per-core structure for managing state about which cores are
5138  * running in the host versus the guest and for exchanging data between
5139  * real mode KVM and CPU running in the host.
5140  * This is only done for the first VM.
5141  * The allocated structure stays even if all VMs have stopped.
5142  * It is only freed when the kvm-hv module is unloaded.
5143  * It's OK for this routine to fail, we just don't support host
5144  * core operations like redirecting H_IPI wakeups.
5145  */
5146 void kvmppc_alloc_host_rm_ops(void)
5147 {
5148 	struct kvmppc_host_rm_ops *ops;
5149 	unsigned long l_ops;
5150 	int cpu, core;
5151 	int size;
5152 
5153 	if (cpu_has_feature(CPU_FTR_ARCH_300))
5154 		return;
5155 
5156 	/* Not the first time here ? */
5157 	if (kvmppc_host_rm_ops_hv != NULL)
5158 		return;
5159 
5160 	ops = kzalloc(sizeof(struct kvmppc_host_rm_ops), GFP_KERNEL);
5161 	if (!ops)
5162 		return;
5163 
5164 	size = cpu_nr_cores() * sizeof(struct kvmppc_host_rm_core);
5165 	ops->rm_core = kzalloc(size, GFP_KERNEL);
5166 
5167 	if (!ops->rm_core) {
5168 		kfree(ops);
5169 		return;
5170 	}
5171 
5172 	cpus_read_lock();
5173 
5174 	for (cpu = 0; cpu < nr_cpu_ids; cpu += threads_per_core) {
5175 		if (!cpu_online(cpu))
5176 			continue;
5177 
5178 		core = cpu >> threads_shift;
5179 		ops->rm_core[core].rm_state.in_host = 1;
5180 	}
5181 
5182 	ops->vcpu_kick = kvmppc_fast_vcpu_kick_hv;
5183 
5184 	/*
5185 	 * Make the contents of the kvmppc_host_rm_ops structure visible
5186 	 * to other CPUs before we assign it to the global variable.
5187 	 * Do an atomic assignment (no locks used here), but if someone
5188 	 * beats us to it, just free our copy and return.
5189 	 */
5190 	smp_wmb();
5191 	l_ops = (unsigned long) ops;
5192 
5193 	if (cmpxchg64((unsigned long *)&kvmppc_host_rm_ops_hv, 0, l_ops)) {
5194 		cpus_read_unlock();
5195 		kfree(ops->rm_core);
5196 		kfree(ops);
5197 		return;
5198 	}
5199 
5200 	cpuhp_setup_state_nocalls_cpuslocked(CPUHP_KVM_PPC_BOOK3S_PREPARE,
5201 					     "ppc/kvm_book3s:prepare",
5202 					     kvmppc_set_host_core,
5203 					     kvmppc_clear_host_core);
5204 	cpus_read_unlock();
5205 }
5206 
5207 void kvmppc_free_host_rm_ops(void)
5208 {
5209 	if (kvmppc_host_rm_ops_hv) {
5210 		cpuhp_remove_state_nocalls(CPUHP_KVM_PPC_BOOK3S_PREPARE);
5211 		kfree(kvmppc_host_rm_ops_hv->rm_core);
5212 		kfree(kvmppc_host_rm_ops_hv);
5213 		kvmppc_host_rm_ops_hv = NULL;
5214 	}
5215 }
5216 #endif
5217 
5218 static int kvmppc_core_init_vm_hv(struct kvm *kvm)
5219 {
5220 	unsigned long lpcr, lpid;
5221 	int ret;
5222 
5223 	mutex_init(&kvm->arch.uvmem_lock);
5224 	INIT_LIST_HEAD(&kvm->arch.uvmem_pfns);
5225 	mutex_init(&kvm->arch.mmu_setup_lock);
5226 
5227 	/* Allocate the guest's logical partition ID */
5228 
5229 	lpid = kvmppc_alloc_lpid();
5230 	if ((long)lpid < 0)
5231 		return -ENOMEM;
5232 	kvm->arch.lpid = lpid;
5233 
5234 	kvmppc_alloc_host_rm_ops();
5235 
5236 	kvmhv_vm_nested_init(kvm);
5237 
5238 	/*
5239 	 * Since we don't flush the TLB when tearing down a VM,
5240 	 * and this lpid might have previously been used,
5241 	 * make sure we flush on each core before running the new VM.
5242 	 * On POWER9, the tlbie in mmu_partition_table_set_entry()
5243 	 * does this flush for us.
5244 	 */
5245 	if (!cpu_has_feature(CPU_FTR_ARCH_300))
5246 		cpumask_setall(&kvm->arch.need_tlb_flush);
5247 
5248 	/* Start out with the default set of hcalls enabled */
5249 	memcpy(kvm->arch.enabled_hcalls, default_enabled_hcalls,
5250 	       sizeof(kvm->arch.enabled_hcalls));
5251 
5252 	if (!cpu_has_feature(CPU_FTR_ARCH_300))
5253 		kvm->arch.host_sdr1 = mfspr(SPRN_SDR1);
5254 
5255 	/* Init LPCR for virtual RMA mode */
5256 	if (cpu_has_feature(CPU_FTR_HVMODE)) {
5257 		kvm->arch.host_lpid = mfspr(SPRN_LPID);
5258 		kvm->arch.host_lpcr = lpcr = mfspr(SPRN_LPCR);
5259 		lpcr &= LPCR_PECE | LPCR_LPES;
5260 	} else {
5261 		lpcr = 0;
5262 	}
5263 	lpcr |= (4UL << LPCR_DPFD_SH) | LPCR_HDICE |
5264 		LPCR_VPM0 | LPCR_VPM1;
5265 	kvm->arch.vrma_slb_v = SLB_VSID_B_1T |
5266 		(VRMA_VSID << SLB_VSID_SHIFT_1T);
5267 	/* On POWER8 turn on online bit to enable PURR/SPURR */
5268 	if (cpu_has_feature(CPU_FTR_ARCH_207S))
5269 		lpcr |= LPCR_ONL;
5270 	/*
5271 	 * On POWER9, VPM0 bit is reserved (VPM0=1 behaviour is assumed)
5272 	 * Set HVICE bit to enable hypervisor virtualization interrupts.
5273 	 * Set HEIC to prevent OS interrupts to go to hypervisor (should
5274 	 * be unnecessary but better safe than sorry in case we re-enable
5275 	 * EE in HV mode with this LPCR still set)
5276 	 */
5277 	if (cpu_has_feature(CPU_FTR_ARCH_300)) {
5278 		lpcr &= ~LPCR_VPM0;
5279 		lpcr |= LPCR_HVICE | LPCR_HEIC;
5280 
5281 		/*
5282 		 * If xive is enabled, we route 0x500 interrupts directly
5283 		 * to the guest.
5284 		 */
5285 		if (xics_on_xive())
5286 			lpcr |= LPCR_LPES;
5287 	}
5288 
5289 	/*
5290 	 * If the host uses radix, the guest starts out as radix.
5291 	 */
5292 	if (radix_enabled()) {
5293 		kvm->arch.radix = 1;
5294 		kvm->arch.mmu_ready = 1;
5295 		lpcr &= ~LPCR_VPM1;
5296 		lpcr |= LPCR_UPRT | LPCR_GTSE | LPCR_HR;
5297 		if (cpu_has_feature(CPU_FTR_HVMODE) &&
5298 		    cpu_has_feature(CPU_FTR_ARCH_31) &&
5299 		    (kvm->arch.host_lpcr & LPCR_HAIL))
5300 			lpcr |= LPCR_HAIL;
5301 		ret = kvmppc_init_vm_radix(kvm);
5302 		if (ret) {
5303 			kvmppc_free_lpid(kvm->arch.lpid);
5304 			return ret;
5305 		}
5306 		kvmppc_setup_partition_table(kvm);
5307 	}
5308 
5309 	verify_lpcr(kvm, lpcr);
5310 	kvm->arch.lpcr = lpcr;
5311 
5312 	/* Initialization for future HPT resizes */
5313 	kvm->arch.resize_hpt = NULL;
5314 
5315 	/*
5316 	 * Work out how many sets the TLB has, for the use of
5317 	 * the TLB invalidation loop in book3s_hv_rmhandlers.S.
5318 	 */
5319 	if (cpu_has_feature(CPU_FTR_ARCH_31)) {
5320 		/*
5321 		 * P10 will flush all the congruence class with a single tlbiel
5322 		 */
5323 		kvm->arch.tlb_sets = 1;
5324 	} else if (radix_enabled())
5325 		kvm->arch.tlb_sets = POWER9_TLB_SETS_RADIX;	/* 128 */
5326 	else if (cpu_has_feature(CPU_FTR_ARCH_300))
5327 		kvm->arch.tlb_sets = POWER9_TLB_SETS_HASH;	/* 256 */
5328 	else if (cpu_has_feature(CPU_FTR_ARCH_207S))
5329 		kvm->arch.tlb_sets = POWER8_TLB_SETS;		/* 512 */
5330 	else
5331 		kvm->arch.tlb_sets = POWER7_TLB_SETS;		/* 128 */
5332 
5333 	/*
5334 	 * Track that we now have a HV mode VM active. This blocks secondary
5335 	 * CPU threads from coming online.
5336 	 */
5337 	if (!cpu_has_feature(CPU_FTR_ARCH_300))
5338 		kvm_hv_vm_activated();
5339 
5340 	/*
5341 	 * Initialize smt_mode depending on processor.
5342 	 * POWER8 and earlier have to use "strict" threading, where
5343 	 * all vCPUs in a vcore have to run on the same (sub)core,
5344 	 * whereas on POWER9 the threads can each run a different
5345 	 * guest.
5346 	 */
5347 	if (!cpu_has_feature(CPU_FTR_ARCH_300))
5348 		kvm->arch.smt_mode = threads_per_subcore;
5349 	else
5350 		kvm->arch.smt_mode = 1;
5351 	kvm->arch.emul_smt_mode = 1;
5352 
5353 	return 0;
5354 }
5355 
5356 static int kvmppc_arch_create_vm_debugfs_hv(struct kvm *kvm)
5357 {
5358 	kvmppc_mmu_debugfs_init(kvm);
5359 	if (radix_enabled())
5360 		kvmhv_radix_debugfs_init(kvm);
5361 	return 0;
5362 }
5363 
5364 static void kvmppc_free_vcores(struct kvm *kvm)
5365 {
5366 	long int i;
5367 
5368 	for (i = 0; i < KVM_MAX_VCORES; ++i)
5369 		kfree(kvm->arch.vcores[i]);
5370 	kvm->arch.online_vcores = 0;
5371 }
5372 
5373 static void kvmppc_core_destroy_vm_hv(struct kvm *kvm)
5374 {
5375 	if (!cpu_has_feature(CPU_FTR_ARCH_300))
5376 		kvm_hv_vm_deactivated();
5377 
5378 	kvmppc_free_vcores(kvm);
5379 
5380 
5381 	if (kvm_is_radix(kvm))
5382 		kvmppc_free_radix(kvm);
5383 	else
5384 		kvmppc_free_hpt(&kvm->arch.hpt);
5385 
5386 	/* Perform global invalidation and return lpid to the pool */
5387 	if (cpu_has_feature(CPU_FTR_ARCH_300)) {
5388 		if (nesting_enabled(kvm))
5389 			kvmhv_release_all_nested(kvm);
5390 		kvm->arch.process_table = 0;
5391 		if (kvm->arch.secure_guest)
5392 			uv_svm_terminate(kvm->arch.lpid);
5393 		kvmhv_set_ptbl_entry(kvm->arch.lpid, 0, 0);
5394 	}
5395 
5396 	kvmppc_free_lpid(kvm->arch.lpid);
5397 
5398 	kvmppc_free_pimap(kvm);
5399 }
5400 
5401 /* We don't need to emulate any privileged instructions or dcbz */
5402 static int kvmppc_core_emulate_op_hv(struct kvm_vcpu *vcpu,
5403 				     unsigned int inst, int *advance)
5404 {
5405 	return EMULATE_FAIL;
5406 }
5407 
5408 static int kvmppc_core_emulate_mtspr_hv(struct kvm_vcpu *vcpu, int sprn,
5409 					ulong spr_val)
5410 {
5411 	return EMULATE_FAIL;
5412 }
5413 
5414 static int kvmppc_core_emulate_mfspr_hv(struct kvm_vcpu *vcpu, int sprn,
5415 					ulong *spr_val)
5416 {
5417 	return EMULATE_FAIL;
5418 }
5419 
5420 static int kvmppc_core_check_processor_compat_hv(void)
5421 {
5422 	if (cpu_has_feature(CPU_FTR_HVMODE) &&
5423 	    cpu_has_feature(CPU_FTR_ARCH_206))
5424 		return 0;
5425 
5426 	/* POWER9 in radix mode is capable of being a nested hypervisor. */
5427 	if (cpu_has_feature(CPU_FTR_ARCH_300) && radix_enabled())
5428 		return 0;
5429 
5430 	return -EIO;
5431 }
5432 
5433 #ifdef CONFIG_KVM_XICS
5434 
5435 void kvmppc_free_pimap(struct kvm *kvm)
5436 {
5437 	kfree(kvm->arch.pimap);
5438 }
5439 
5440 static struct kvmppc_passthru_irqmap *kvmppc_alloc_pimap(void)
5441 {
5442 	return kzalloc(sizeof(struct kvmppc_passthru_irqmap), GFP_KERNEL);
5443 }
5444 
5445 static int kvmppc_set_passthru_irq(struct kvm *kvm, int host_irq, int guest_gsi)
5446 {
5447 	struct irq_desc *desc;
5448 	struct kvmppc_irq_map *irq_map;
5449 	struct kvmppc_passthru_irqmap *pimap;
5450 	struct irq_chip *chip;
5451 	int i, rc = 0;
5452 	struct irq_data *host_data;
5453 
5454 	if (!kvm_irq_bypass)
5455 		return 1;
5456 
5457 	desc = irq_to_desc(host_irq);
5458 	if (!desc)
5459 		return -EIO;
5460 
5461 	mutex_lock(&kvm->lock);
5462 
5463 	pimap = kvm->arch.pimap;
5464 	if (pimap == NULL) {
5465 		/* First call, allocate structure to hold IRQ map */
5466 		pimap = kvmppc_alloc_pimap();
5467 		if (pimap == NULL) {
5468 			mutex_unlock(&kvm->lock);
5469 			return -ENOMEM;
5470 		}
5471 		kvm->arch.pimap = pimap;
5472 	}
5473 
5474 	/*
5475 	 * For now, we only support interrupts for which the EOI operation
5476 	 * is an OPAL call followed by a write to XIRR, since that's
5477 	 * what our real-mode EOI code does, or a XIVE interrupt
5478 	 */
5479 	chip = irq_data_get_irq_chip(&desc->irq_data);
5480 	if (!chip || !is_pnv_opal_msi(chip)) {
5481 		pr_warn("kvmppc_set_passthru_irq_hv: Could not assign IRQ map for (%d,%d)\n",
5482 			host_irq, guest_gsi);
5483 		mutex_unlock(&kvm->lock);
5484 		return -ENOENT;
5485 	}
5486 
5487 	/*
5488 	 * See if we already have an entry for this guest IRQ number.
5489 	 * If it's mapped to a hardware IRQ number, that's an error,
5490 	 * otherwise re-use this entry.
5491 	 */
5492 	for (i = 0; i < pimap->n_mapped; i++) {
5493 		if (guest_gsi == pimap->mapped[i].v_hwirq) {
5494 			if (pimap->mapped[i].r_hwirq) {
5495 				mutex_unlock(&kvm->lock);
5496 				return -EINVAL;
5497 			}
5498 			break;
5499 		}
5500 	}
5501 
5502 	if (i == KVMPPC_PIRQ_MAPPED) {
5503 		mutex_unlock(&kvm->lock);
5504 		return -EAGAIN;		/* table is full */
5505 	}
5506 
5507 	irq_map = &pimap->mapped[i];
5508 
5509 	irq_map->v_hwirq = guest_gsi;
5510 	irq_map->desc = desc;
5511 
5512 	/*
5513 	 * Order the above two stores before the next to serialize with
5514 	 * the KVM real mode handler.
5515 	 */
5516 	smp_wmb();
5517 
5518 	/*
5519 	 * The 'host_irq' number is mapped in the PCI-MSI domain but
5520 	 * the underlying calls, which will EOI the interrupt in real
5521 	 * mode, need an HW IRQ number mapped in the XICS IRQ domain.
5522 	 */
5523 	host_data = irq_domain_get_irq_data(irq_get_default_host(), host_irq);
5524 	irq_map->r_hwirq = (unsigned int)irqd_to_hwirq(host_data);
5525 
5526 	if (i == pimap->n_mapped)
5527 		pimap->n_mapped++;
5528 
5529 	if (xics_on_xive())
5530 		rc = kvmppc_xive_set_mapped(kvm, guest_gsi, host_irq);
5531 	else
5532 		kvmppc_xics_set_mapped(kvm, guest_gsi, irq_map->r_hwirq);
5533 	if (rc)
5534 		irq_map->r_hwirq = 0;
5535 
5536 	mutex_unlock(&kvm->lock);
5537 
5538 	return 0;
5539 }
5540 
5541 static int kvmppc_clr_passthru_irq(struct kvm *kvm, int host_irq, int guest_gsi)
5542 {
5543 	struct irq_desc *desc;
5544 	struct kvmppc_passthru_irqmap *pimap;
5545 	int i, rc = 0;
5546 
5547 	if (!kvm_irq_bypass)
5548 		return 0;
5549 
5550 	desc = irq_to_desc(host_irq);
5551 	if (!desc)
5552 		return -EIO;
5553 
5554 	mutex_lock(&kvm->lock);
5555 	if (!kvm->arch.pimap)
5556 		goto unlock;
5557 
5558 	pimap = kvm->arch.pimap;
5559 
5560 	for (i = 0; i < pimap->n_mapped; i++) {
5561 		if (guest_gsi == pimap->mapped[i].v_hwirq)
5562 			break;
5563 	}
5564 
5565 	if (i == pimap->n_mapped) {
5566 		mutex_unlock(&kvm->lock);
5567 		return -ENODEV;
5568 	}
5569 
5570 	if (xics_on_xive())
5571 		rc = kvmppc_xive_clr_mapped(kvm, guest_gsi, host_irq);
5572 	else
5573 		kvmppc_xics_clr_mapped(kvm, guest_gsi, pimap->mapped[i].r_hwirq);
5574 
5575 	/* invalidate the entry (what do do on error from the above ?) */
5576 	pimap->mapped[i].r_hwirq = 0;
5577 
5578 	/*
5579 	 * We don't free this structure even when the count goes to
5580 	 * zero. The structure is freed when we destroy the VM.
5581 	 */
5582  unlock:
5583 	mutex_unlock(&kvm->lock);
5584 	return rc;
5585 }
5586 
5587 static int kvmppc_irq_bypass_add_producer_hv(struct irq_bypass_consumer *cons,
5588 					     struct irq_bypass_producer *prod)
5589 {
5590 	int ret = 0;
5591 	struct kvm_kernel_irqfd *irqfd =
5592 		container_of(cons, struct kvm_kernel_irqfd, consumer);
5593 
5594 	irqfd->producer = prod;
5595 
5596 	ret = kvmppc_set_passthru_irq(irqfd->kvm, prod->irq, irqfd->gsi);
5597 	if (ret)
5598 		pr_info("kvmppc_set_passthru_irq (irq %d, gsi %d) fails: %d\n",
5599 			prod->irq, irqfd->gsi, ret);
5600 
5601 	return ret;
5602 }
5603 
5604 static void kvmppc_irq_bypass_del_producer_hv(struct irq_bypass_consumer *cons,
5605 					      struct irq_bypass_producer *prod)
5606 {
5607 	int ret;
5608 	struct kvm_kernel_irqfd *irqfd =
5609 		container_of(cons, struct kvm_kernel_irqfd, consumer);
5610 
5611 	irqfd->producer = NULL;
5612 
5613 	/*
5614 	 * When producer of consumer is unregistered, we change back to
5615 	 * default external interrupt handling mode - KVM real mode
5616 	 * will switch back to host.
5617 	 */
5618 	ret = kvmppc_clr_passthru_irq(irqfd->kvm, prod->irq, irqfd->gsi);
5619 	if (ret)
5620 		pr_warn("kvmppc_clr_passthru_irq (irq %d, gsi %d) fails: %d\n",
5621 			prod->irq, irqfd->gsi, ret);
5622 }
5623 #endif
5624 
5625 static long kvm_arch_vm_ioctl_hv(struct file *filp,
5626 				 unsigned int ioctl, unsigned long arg)
5627 {
5628 	struct kvm *kvm __maybe_unused = filp->private_data;
5629 	void __user *argp = (void __user *)arg;
5630 	long r;
5631 
5632 	switch (ioctl) {
5633 
5634 	case KVM_PPC_ALLOCATE_HTAB: {
5635 		u32 htab_order;
5636 
5637 		/* If we're a nested hypervisor, we currently only support radix */
5638 		if (kvmhv_on_pseries()) {
5639 			r = -EOPNOTSUPP;
5640 			break;
5641 		}
5642 
5643 		r = -EFAULT;
5644 		if (get_user(htab_order, (u32 __user *)argp))
5645 			break;
5646 		r = kvmppc_alloc_reset_hpt(kvm, htab_order);
5647 		if (r)
5648 			break;
5649 		r = 0;
5650 		break;
5651 	}
5652 
5653 	case KVM_PPC_GET_HTAB_FD: {
5654 		struct kvm_get_htab_fd ghf;
5655 
5656 		r = -EFAULT;
5657 		if (copy_from_user(&ghf, argp, sizeof(ghf)))
5658 			break;
5659 		r = kvm_vm_ioctl_get_htab_fd(kvm, &ghf);
5660 		break;
5661 	}
5662 
5663 	case KVM_PPC_RESIZE_HPT_PREPARE: {
5664 		struct kvm_ppc_resize_hpt rhpt;
5665 
5666 		r = -EFAULT;
5667 		if (copy_from_user(&rhpt, argp, sizeof(rhpt)))
5668 			break;
5669 
5670 		r = kvm_vm_ioctl_resize_hpt_prepare(kvm, &rhpt);
5671 		break;
5672 	}
5673 
5674 	case KVM_PPC_RESIZE_HPT_COMMIT: {
5675 		struct kvm_ppc_resize_hpt rhpt;
5676 
5677 		r = -EFAULT;
5678 		if (copy_from_user(&rhpt, argp, sizeof(rhpt)))
5679 			break;
5680 
5681 		r = kvm_vm_ioctl_resize_hpt_commit(kvm, &rhpt);
5682 		break;
5683 	}
5684 
5685 	default:
5686 		r = -ENOTTY;
5687 	}
5688 
5689 	return r;
5690 }
5691 
5692 /*
5693  * List of hcall numbers to enable by default.
5694  * For compatibility with old userspace, we enable by default
5695  * all hcalls that were implemented before the hcall-enabling
5696  * facility was added.  Note this list should not include H_RTAS.
5697  */
5698 static unsigned int default_hcall_list[] = {
5699 	H_REMOVE,
5700 	H_ENTER,
5701 	H_READ,
5702 	H_PROTECT,
5703 	H_BULK_REMOVE,
5704 #ifdef CONFIG_SPAPR_TCE_IOMMU
5705 	H_GET_TCE,
5706 	H_PUT_TCE,
5707 #endif
5708 	H_SET_DABR,
5709 	H_SET_XDABR,
5710 	H_CEDE,
5711 	H_PROD,
5712 	H_CONFER,
5713 	H_REGISTER_VPA,
5714 #ifdef CONFIG_KVM_XICS
5715 	H_EOI,
5716 	H_CPPR,
5717 	H_IPI,
5718 	H_IPOLL,
5719 	H_XIRR,
5720 	H_XIRR_X,
5721 #endif
5722 	0
5723 };
5724 
5725 static void init_default_hcalls(void)
5726 {
5727 	int i;
5728 	unsigned int hcall;
5729 
5730 	for (i = 0; default_hcall_list[i]; ++i) {
5731 		hcall = default_hcall_list[i];
5732 		WARN_ON(!kvmppc_hcall_impl_hv(hcall));
5733 		__set_bit(hcall / 4, default_enabled_hcalls);
5734 	}
5735 }
5736 
5737 static int kvmhv_configure_mmu(struct kvm *kvm, struct kvm_ppc_mmuv3_cfg *cfg)
5738 {
5739 	unsigned long lpcr;
5740 	int radix;
5741 	int err;
5742 
5743 	/* If not on a POWER9, reject it */
5744 	if (!cpu_has_feature(CPU_FTR_ARCH_300))
5745 		return -ENODEV;
5746 
5747 	/* If any unknown flags set, reject it */
5748 	if (cfg->flags & ~(KVM_PPC_MMUV3_RADIX | KVM_PPC_MMUV3_GTSE))
5749 		return -EINVAL;
5750 
5751 	/* GR (guest radix) bit in process_table field must match */
5752 	radix = !!(cfg->flags & KVM_PPC_MMUV3_RADIX);
5753 	if (!!(cfg->process_table & PATB_GR) != radix)
5754 		return -EINVAL;
5755 
5756 	/* Process table size field must be reasonable, i.e. <= 24 */
5757 	if ((cfg->process_table & PRTS_MASK) > 24)
5758 		return -EINVAL;
5759 
5760 	/* We can change a guest to/from radix now, if the host is radix */
5761 	if (radix && !radix_enabled())
5762 		return -EINVAL;
5763 
5764 	/* If we're a nested hypervisor, we currently only support radix */
5765 	if (kvmhv_on_pseries() && !radix)
5766 		return -EINVAL;
5767 
5768 	mutex_lock(&kvm->arch.mmu_setup_lock);
5769 	if (radix != kvm_is_radix(kvm)) {
5770 		if (kvm->arch.mmu_ready) {
5771 			kvm->arch.mmu_ready = 0;
5772 			/* order mmu_ready vs. vcpus_running */
5773 			smp_mb();
5774 			if (atomic_read(&kvm->arch.vcpus_running)) {
5775 				kvm->arch.mmu_ready = 1;
5776 				err = -EBUSY;
5777 				goto out_unlock;
5778 			}
5779 		}
5780 		if (radix)
5781 			err = kvmppc_switch_mmu_to_radix(kvm);
5782 		else
5783 			err = kvmppc_switch_mmu_to_hpt(kvm);
5784 		if (err)
5785 			goto out_unlock;
5786 	}
5787 
5788 	kvm->arch.process_table = cfg->process_table;
5789 	kvmppc_setup_partition_table(kvm);
5790 
5791 	lpcr = (cfg->flags & KVM_PPC_MMUV3_GTSE) ? LPCR_GTSE : 0;
5792 	kvmppc_update_lpcr(kvm, lpcr, LPCR_GTSE);
5793 	err = 0;
5794 
5795  out_unlock:
5796 	mutex_unlock(&kvm->arch.mmu_setup_lock);
5797 	return err;
5798 }
5799 
5800 static int kvmhv_enable_nested(struct kvm *kvm)
5801 {
5802 	if (!nested)
5803 		return -EPERM;
5804 	if (!cpu_has_feature(CPU_FTR_ARCH_300))
5805 		return -ENODEV;
5806 	if (!radix_enabled())
5807 		return -ENODEV;
5808 
5809 	/* kvm == NULL means the caller is testing if the capability exists */
5810 	if (kvm)
5811 		kvm->arch.nested_enable = true;
5812 	return 0;
5813 }
5814 
5815 static int kvmhv_load_from_eaddr(struct kvm_vcpu *vcpu, ulong *eaddr, void *ptr,
5816 				 int size)
5817 {
5818 	int rc = -EINVAL;
5819 
5820 	if (kvmhv_vcpu_is_radix(vcpu)) {
5821 		rc = kvmhv_copy_from_guest_radix(vcpu, *eaddr, ptr, size);
5822 
5823 		if (rc > 0)
5824 			rc = -EINVAL;
5825 	}
5826 
5827 	/* For now quadrants are the only way to access nested guest memory */
5828 	if (rc && vcpu->arch.nested)
5829 		rc = -EAGAIN;
5830 
5831 	return rc;
5832 }
5833 
5834 static int kvmhv_store_to_eaddr(struct kvm_vcpu *vcpu, ulong *eaddr, void *ptr,
5835 				int size)
5836 {
5837 	int rc = -EINVAL;
5838 
5839 	if (kvmhv_vcpu_is_radix(vcpu)) {
5840 		rc = kvmhv_copy_to_guest_radix(vcpu, *eaddr, ptr, size);
5841 
5842 		if (rc > 0)
5843 			rc = -EINVAL;
5844 	}
5845 
5846 	/* For now quadrants are the only way to access nested guest memory */
5847 	if (rc && vcpu->arch.nested)
5848 		rc = -EAGAIN;
5849 
5850 	return rc;
5851 }
5852 
5853 static void unpin_vpa_reset(struct kvm *kvm, struct kvmppc_vpa *vpa)
5854 {
5855 	unpin_vpa(kvm, vpa);
5856 	vpa->gpa = 0;
5857 	vpa->pinned_addr = NULL;
5858 	vpa->dirty = false;
5859 	vpa->update_pending = 0;
5860 }
5861 
5862 /*
5863  * Enable a guest to become a secure VM, or test whether
5864  * that could be enabled.
5865  * Called when the KVM_CAP_PPC_SECURE_GUEST capability is
5866  * tested (kvm == NULL) or enabled (kvm != NULL).
5867  */
5868 static int kvmhv_enable_svm(struct kvm *kvm)
5869 {
5870 	if (!kvmppc_uvmem_available())
5871 		return -EINVAL;
5872 	if (kvm)
5873 		kvm->arch.svm_enabled = 1;
5874 	return 0;
5875 }
5876 
5877 /*
5878  *  IOCTL handler to turn off secure mode of guest
5879  *
5880  * - Release all device pages
5881  * - Issue ucall to terminate the guest on the UV side
5882  * - Unpin the VPA pages.
5883  * - Reinit the partition scoped page tables
5884  */
5885 static int kvmhv_svm_off(struct kvm *kvm)
5886 {
5887 	struct kvm_vcpu *vcpu;
5888 	int mmu_was_ready;
5889 	int srcu_idx;
5890 	int ret = 0;
5891 	unsigned long i;
5892 
5893 	if (!(kvm->arch.secure_guest & KVMPPC_SECURE_INIT_START))
5894 		return ret;
5895 
5896 	mutex_lock(&kvm->arch.mmu_setup_lock);
5897 	mmu_was_ready = kvm->arch.mmu_ready;
5898 	if (kvm->arch.mmu_ready) {
5899 		kvm->arch.mmu_ready = 0;
5900 		/* order mmu_ready vs. vcpus_running */
5901 		smp_mb();
5902 		if (atomic_read(&kvm->arch.vcpus_running)) {
5903 			kvm->arch.mmu_ready = 1;
5904 			ret = -EBUSY;
5905 			goto out;
5906 		}
5907 	}
5908 
5909 	srcu_idx = srcu_read_lock(&kvm->srcu);
5910 	for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
5911 		struct kvm_memory_slot *memslot;
5912 		struct kvm_memslots *slots = __kvm_memslots(kvm, i);
5913 		int bkt;
5914 
5915 		if (!slots)
5916 			continue;
5917 
5918 		kvm_for_each_memslot(memslot, bkt, slots) {
5919 			kvmppc_uvmem_drop_pages(memslot, kvm, true);
5920 			uv_unregister_mem_slot(kvm->arch.lpid, memslot->id);
5921 		}
5922 	}
5923 	srcu_read_unlock(&kvm->srcu, srcu_idx);
5924 
5925 	ret = uv_svm_terminate(kvm->arch.lpid);
5926 	if (ret != U_SUCCESS) {
5927 		ret = -EINVAL;
5928 		goto out;
5929 	}
5930 
5931 	/*
5932 	 * When secure guest is reset, all the guest pages are sent
5933 	 * to UV via UV_PAGE_IN before the non-boot vcpus get a
5934 	 * chance to run and unpin their VPA pages. Unpinning of all
5935 	 * VPA pages is done here explicitly so that VPA pages
5936 	 * can be migrated to the secure side.
5937 	 *
5938 	 * This is required to for the secure SMP guest to reboot
5939 	 * correctly.
5940 	 */
5941 	kvm_for_each_vcpu(i, vcpu, kvm) {
5942 		spin_lock(&vcpu->arch.vpa_update_lock);
5943 		unpin_vpa_reset(kvm, &vcpu->arch.dtl);
5944 		unpin_vpa_reset(kvm, &vcpu->arch.slb_shadow);
5945 		unpin_vpa_reset(kvm, &vcpu->arch.vpa);
5946 		spin_unlock(&vcpu->arch.vpa_update_lock);
5947 	}
5948 
5949 	kvmppc_setup_partition_table(kvm);
5950 	kvm->arch.secure_guest = 0;
5951 	kvm->arch.mmu_ready = mmu_was_ready;
5952 out:
5953 	mutex_unlock(&kvm->arch.mmu_setup_lock);
5954 	return ret;
5955 }
5956 
5957 static int kvmhv_enable_dawr1(struct kvm *kvm)
5958 {
5959 	if (!cpu_has_feature(CPU_FTR_DAWR1))
5960 		return -ENODEV;
5961 
5962 	/* kvm == NULL means the caller is testing if the capability exists */
5963 	if (kvm)
5964 		kvm->arch.dawr1_enabled = true;
5965 	return 0;
5966 }
5967 
5968 static bool kvmppc_hash_v3_possible(void)
5969 {
5970 	if (!cpu_has_feature(CPU_FTR_ARCH_300))
5971 		return false;
5972 
5973 	if (!cpu_has_feature(CPU_FTR_HVMODE))
5974 		return false;
5975 
5976 	/*
5977 	 * POWER9 chips before version 2.02 can't have some threads in
5978 	 * HPT mode and some in radix mode on the same core.
5979 	 */
5980 	if (radix_enabled()) {
5981 		unsigned int pvr = mfspr(SPRN_PVR);
5982 		if ((pvr >> 16) == PVR_POWER9 &&
5983 		    (((pvr & 0xe000) == 0 && (pvr & 0xfff) < 0x202) ||
5984 		     ((pvr & 0xe000) == 0x2000 && (pvr & 0xfff) < 0x101)))
5985 			return false;
5986 	}
5987 
5988 	return true;
5989 }
5990 
5991 static struct kvmppc_ops kvm_ops_hv = {
5992 	.get_sregs = kvm_arch_vcpu_ioctl_get_sregs_hv,
5993 	.set_sregs = kvm_arch_vcpu_ioctl_set_sregs_hv,
5994 	.get_one_reg = kvmppc_get_one_reg_hv,
5995 	.set_one_reg = kvmppc_set_one_reg_hv,
5996 	.vcpu_load   = kvmppc_core_vcpu_load_hv,
5997 	.vcpu_put    = kvmppc_core_vcpu_put_hv,
5998 	.inject_interrupt = kvmppc_inject_interrupt_hv,
5999 	.set_msr     = kvmppc_set_msr_hv,
6000 	.vcpu_run    = kvmppc_vcpu_run_hv,
6001 	.vcpu_create = kvmppc_core_vcpu_create_hv,
6002 	.vcpu_free   = kvmppc_core_vcpu_free_hv,
6003 	.check_requests = kvmppc_core_check_requests_hv,
6004 	.get_dirty_log  = kvm_vm_ioctl_get_dirty_log_hv,
6005 	.flush_memslot  = kvmppc_core_flush_memslot_hv,
6006 	.prepare_memory_region = kvmppc_core_prepare_memory_region_hv,
6007 	.commit_memory_region  = kvmppc_core_commit_memory_region_hv,
6008 	.unmap_gfn_range = kvm_unmap_gfn_range_hv,
6009 	.age_gfn = kvm_age_gfn_hv,
6010 	.test_age_gfn = kvm_test_age_gfn_hv,
6011 	.set_spte_gfn = kvm_set_spte_gfn_hv,
6012 	.free_memslot = kvmppc_core_free_memslot_hv,
6013 	.init_vm =  kvmppc_core_init_vm_hv,
6014 	.destroy_vm = kvmppc_core_destroy_vm_hv,
6015 	.get_smmu_info = kvm_vm_ioctl_get_smmu_info_hv,
6016 	.emulate_op = kvmppc_core_emulate_op_hv,
6017 	.emulate_mtspr = kvmppc_core_emulate_mtspr_hv,
6018 	.emulate_mfspr = kvmppc_core_emulate_mfspr_hv,
6019 	.fast_vcpu_kick = kvmppc_fast_vcpu_kick_hv,
6020 	.arch_vm_ioctl  = kvm_arch_vm_ioctl_hv,
6021 	.hcall_implemented = kvmppc_hcall_impl_hv,
6022 #ifdef CONFIG_KVM_XICS
6023 	.irq_bypass_add_producer = kvmppc_irq_bypass_add_producer_hv,
6024 	.irq_bypass_del_producer = kvmppc_irq_bypass_del_producer_hv,
6025 #endif
6026 	.configure_mmu = kvmhv_configure_mmu,
6027 	.get_rmmu_info = kvmhv_get_rmmu_info,
6028 	.set_smt_mode = kvmhv_set_smt_mode,
6029 	.enable_nested = kvmhv_enable_nested,
6030 	.load_from_eaddr = kvmhv_load_from_eaddr,
6031 	.store_to_eaddr = kvmhv_store_to_eaddr,
6032 	.enable_svm = kvmhv_enable_svm,
6033 	.svm_off = kvmhv_svm_off,
6034 	.enable_dawr1 = kvmhv_enable_dawr1,
6035 	.hash_v3_possible = kvmppc_hash_v3_possible,
6036 	.create_vcpu_debugfs = kvmppc_arch_create_vcpu_debugfs_hv,
6037 	.create_vm_debugfs = kvmppc_arch_create_vm_debugfs_hv,
6038 };
6039 
6040 static int kvm_init_subcore_bitmap(void)
6041 {
6042 	int i, j;
6043 	int nr_cores = cpu_nr_cores();
6044 	struct sibling_subcore_state *sibling_subcore_state;
6045 
6046 	for (i = 0; i < nr_cores; i++) {
6047 		int first_cpu = i * threads_per_core;
6048 		int node = cpu_to_node(first_cpu);
6049 
6050 		/* Ignore if it is already allocated. */
6051 		if (paca_ptrs[first_cpu]->sibling_subcore_state)
6052 			continue;
6053 
6054 		sibling_subcore_state =
6055 			kzalloc_node(sizeof(struct sibling_subcore_state),
6056 							GFP_KERNEL, node);
6057 		if (!sibling_subcore_state)
6058 			return -ENOMEM;
6059 
6060 
6061 		for (j = 0; j < threads_per_core; j++) {
6062 			int cpu = first_cpu + j;
6063 
6064 			paca_ptrs[cpu]->sibling_subcore_state =
6065 						sibling_subcore_state;
6066 		}
6067 	}
6068 	return 0;
6069 }
6070 
6071 static int kvmppc_radix_possible(void)
6072 {
6073 	return cpu_has_feature(CPU_FTR_ARCH_300) && radix_enabled();
6074 }
6075 
6076 static int kvmppc_book3s_init_hv(void)
6077 {
6078 	int r;
6079 
6080 	if (!tlbie_capable) {
6081 		pr_err("KVM-HV: Host does not support TLBIE\n");
6082 		return -ENODEV;
6083 	}
6084 
6085 	/*
6086 	 * FIXME!! Do we need to check on all cpus ?
6087 	 */
6088 	r = kvmppc_core_check_processor_compat_hv();
6089 	if (r < 0)
6090 		return -ENODEV;
6091 
6092 	r = kvmhv_nested_init();
6093 	if (r)
6094 		return r;
6095 
6096 	if (!cpu_has_feature(CPU_FTR_ARCH_300)) {
6097 		r = kvm_init_subcore_bitmap();
6098 		if (r)
6099 			goto err;
6100 	}
6101 
6102 	/*
6103 	 * We need a way of accessing the XICS interrupt controller,
6104 	 * either directly, via paca_ptrs[cpu]->kvm_hstate.xics_phys, or
6105 	 * indirectly, via OPAL.
6106 	 */
6107 #ifdef CONFIG_SMP
6108 	if (!xics_on_xive() && !kvmhv_on_pseries() &&
6109 	    !local_paca->kvm_hstate.xics_phys) {
6110 		struct device_node *np;
6111 
6112 		np = of_find_compatible_node(NULL, NULL, "ibm,opal-intc");
6113 		if (!np) {
6114 			pr_err("KVM-HV: Cannot determine method for accessing XICS\n");
6115 			r = -ENODEV;
6116 			goto err;
6117 		}
6118 		/* presence of intc confirmed - node can be dropped again */
6119 		of_node_put(np);
6120 	}
6121 #endif
6122 
6123 	init_default_hcalls();
6124 
6125 	init_vcore_lists();
6126 
6127 	r = kvmppc_mmu_hv_init();
6128 	if (r)
6129 		goto err;
6130 
6131 	if (kvmppc_radix_possible()) {
6132 		r = kvmppc_radix_init();
6133 		if (r)
6134 			goto err;
6135 	}
6136 
6137 	r = kvmppc_uvmem_init();
6138 	if (r < 0) {
6139 		pr_err("KVM-HV: kvmppc_uvmem_init failed %d\n", r);
6140 		return r;
6141 	}
6142 
6143 	kvm_ops_hv.owner = THIS_MODULE;
6144 	kvmppc_hv_ops = &kvm_ops_hv;
6145 
6146 	return 0;
6147 
6148 err:
6149 	kvmhv_nested_exit();
6150 	kvmppc_radix_exit();
6151 
6152 	return r;
6153 }
6154 
6155 static void kvmppc_book3s_exit_hv(void)
6156 {
6157 	kvmppc_uvmem_free();
6158 	kvmppc_free_host_rm_ops();
6159 	if (kvmppc_radix_possible())
6160 		kvmppc_radix_exit();
6161 	kvmppc_hv_ops = NULL;
6162 	kvmhv_nested_exit();
6163 }
6164 
6165 module_init(kvmppc_book3s_init_hv);
6166 module_exit(kvmppc_book3s_exit_hv);
6167 MODULE_LICENSE("GPL");
6168 MODULE_ALIAS_MISCDEV(KVM_MINOR);
6169 MODULE_ALIAS("devname:kvm");
6170