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