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