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