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