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