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