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