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