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