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