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