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