1 /*
2  * Copyright 2011 Paul Mackerras, IBM Corp. <paulus@au1.ibm.com>
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License, version 2, as
6  * published by the Free Software Foundation.
7  */
8 
9 #include <linux/cpu.h>
10 #include <linux/kvm_host.h>
11 #include <linux/preempt.h>
12 #include <linux/export.h>
13 #include <linux/sched.h>
14 #include <linux/spinlock.h>
15 #include <linux/init.h>
16 #include <linux/memblock.h>
17 #include <linux/sizes.h>
18 #include <linux/cma.h>
19 #include <linux/bitops.h>
20 
21 #include <asm/cputable.h>
22 #include <asm/kvm_ppc.h>
23 #include <asm/kvm_book3s.h>
24 #include <asm/archrandom.h>
25 #include <asm/xics.h>
26 #include <asm/xive.h>
27 #include <asm/dbell.h>
28 #include <asm/cputhreads.h>
29 #include <asm/io.h>
30 #include <asm/opal.h>
31 #include <asm/smp.h>
32 
33 #define KVM_CMA_CHUNK_ORDER	18
34 
35 #include "book3s_xics.h"
36 #include "book3s_xive.h"
37 
38 /*
39  * The XIVE module will populate these when it loads
40  */
41 unsigned long (*__xive_vm_h_xirr)(struct kvm_vcpu *vcpu);
42 unsigned long (*__xive_vm_h_ipoll)(struct kvm_vcpu *vcpu, unsigned long server);
43 int (*__xive_vm_h_ipi)(struct kvm_vcpu *vcpu, unsigned long server,
44 		       unsigned long mfrr);
45 int (*__xive_vm_h_cppr)(struct kvm_vcpu *vcpu, unsigned long cppr);
46 int (*__xive_vm_h_eoi)(struct kvm_vcpu *vcpu, unsigned long xirr);
47 EXPORT_SYMBOL_GPL(__xive_vm_h_xirr);
48 EXPORT_SYMBOL_GPL(__xive_vm_h_ipoll);
49 EXPORT_SYMBOL_GPL(__xive_vm_h_ipi);
50 EXPORT_SYMBOL_GPL(__xive_vm_h_cppr);
51 EXPORT_SYMBOL_GPL(__xive_vm_h_eoi);
52 
53 /*
54  * Hash page table alignment on newer cpus(CPU_FTR_ARCH_206)
55  * should be power of 2.
56  */
57 #define HPT_ALIGN_PAGES		((1 << 18) >> PAGE_SHIFT) /* 256k */
58 /*
59  * By default we reserve 5% of memory for hash pagetable allocation.
60  */
61 static unsigned long kvm_cma_resv_ratio = 5;
62 
63 static struct cma *kvm_cma;
64 
65 static int __init early_parse_kvm_cma_resv(char *p)
66 {
67 	pr_debug("%s(%s)\n", __func__, p);
68 	if (!p)
69 		return -EINVAL;
70 	return kstrtoul(p, 0, &kvm_cma_resv_ratio);
71 }
72 early_param("kvm_cma_resv_ratio", early_parse_kvm_cma_resv);
73 
74 struct page *kvm_alloc_hpt_cma(unsigned long nr_pages)
75 {
76 	VM_BUG_ON(order_base_2(nr_pages) < KVM_CMA_CHUNK_ORDER - PAGE_SHIFT);
77 
78 	return cma_alloc(kvm_cma, nr_pages, order_base_2(HPT_ALIGN_PAGES),
79 			 GFP_KERNEL);
80 }
81 EXPORT_SYMBOL_GPL(kvm_alloc_hpt_cma);
82 
83 void kvm_free_hpt_cma(struct page *page, unsigned long nr_pages)
84 {
85 	cma_release(kvm_cma, page, nr_pages);
86 }
87 EXPORT_SYMBOL_GPL(kvm_free_hpt_cma);
88 
89 /**
90  * kvm_cma_reserve() - reserve area for kvm hash pagetable
91  *
92  * This function reserves memory from early allocator. It should be
93  * called by arch specific code once the memblock allocator
94  * has been activated and all other subsystems have already allocated/reserved
95  * memory.
96  */
97 void __init kvm_cma_reserve(void)
98 {
99 	unsigned long align_size;
100 	struct memblock_region *reg;
101 	phys_addr_t selected_size = 0;
102 
103 	/*
104 	 * We need CMA reservation only when we are in HV mode
105 	 */
106 	if (!cpu_has_feature(CPU_FTR_HVMODE))
107 		return;
108 	/*
109 	 * We cannot use memblock_phys_mem_size() here, because
110 	 * memblock_analyze() has not been called yet.
111 	 */
112 	for_each_memblock(memory, reg)
113 		selected_size += memblock_region_memory_end_pfn(reg) -
114 				 memblock_region_memory_base_pfn(reg);
115 
116 	selected_size = (selected_size * kvm_cma_resv_ratio / 100) << PAGE_SHIFT;
117 	if (selected_size) {
118 		pr_debug("%s: reserving %ld MiB for global area\n", __func__,
119 			 (unsigned long)selected_size / SZ_1M);
120 		align_size = HPT_ALIGN_PAGES << PAGE_SHIFT;
121 		cma_declare_contiguous(0, selected_size, 0, align_size,
122 			KVM_CMA_CHUNK_ORDER - PAGE_SHIFT, false, &kvm_cma);
123 	}
124 }
125 
126 /*
127  * Real-mode H_CONFER implementation.
128  * We check if we are the only vcpu out of this virtual core
129  * still running in the guest and not ceded.  If so, we pop up
130  * to the virtual-mode implementation; if not, just return to
131  * the guest.
132  */
133 long int kvmppc_rm_h_confer(struct kvm_vcpu *vcpu, int target,
134 			    unsigned int yield_count)
135 {
136 	struct kvmppc_vcore *vc = local_paca->kvm_hstate.kvm_vcore;
137 	int ptid = local_paca->kvm_hstate.ptid;
138 	int threads_running;
139 	int threads_ceded;
140 	int threads_conferring;
141 	u64 stop = get_tb() + 10 * tb_ticks_per_usec;
142 	int rv = H_SUCCESS; /* => don't yield */
143 
144 	set_bit(ptid, &vc->conferring_threads);
145 	while ((get_tb() < stop) && !VCORE_IS_EXITING(vc)) {
146 		threads_running = VCORE_ENTRY_MAP(vc);
147 		threads_ceded = vc->napping_threads;
148 		threads_conferring = vc->conferring_threads;
149 		if ((threads_ceded | threads_conferring) == threads_running) {
150 			rv = H_TOO_HARD; /* => do yield */
151 			break;
152 		}
153 	}
154 	clear_bit(ptid, &vc->conferring_threads);
155 	return rv;
156 }
157 
158 /*
159  * When running HV mode KVM we need to block certain operations while KVM VMs
160  * exist in the system. We use a counter of VMs to track this.
161  *
162  * One of the operations we need to block is onlining of secondaries, so we
163  * protect hv_vm_count with get/put_online_cpus().
164  */
165 static atomic_t hv_vm_count;
166 
167 void kvm_hv_vm_activated(void)
168 {
169 	get_online_cpus();
170 	atomic_inc(&hv_vm_count);
171 	put_online_cpus();
172 }
173 EXPORT_SYMBOL_GPL(kvm_hv_vm_activated);
174 
175 void kvm_hv_vm_deactivated(void)
176 {
177 	get_online_cpus();
178 	atomic_dec(&hv_vm_count);
179 	put_online_cpus();
180 }
181 EXPORT_SYMBOL_GPL(kvm_hv_vm_deactivated);
182 
183 bool kvm_hv_mode_active(void)
184 {
185 	return atomic_read(&hv_vm_count) != 0;
186 }
187 
188 extern int hcall_real_table[], hcall_real_table_end[];
189 
190 int kvmppc_hcall_impl_hv_realmode(unsigned long cmd)
191 {
192 	cmd /= 4;
193 	if (cmd < hcall_real_table_end - hcall_real_table &&
194 	    hcall_real_table[cmd])
195 		return 1;
196 
197 	return 0;
198 }
199 EXPORT_SYMBOL_GPL(kvmppc_hcall_impl_hv_realmode);
200 
201 int kvmppc_hwrng_present(void)
202 {
203 	return powernv_hwrng_present();
204 }
205 EXPORT_SYMBOL_GPL(kvmppc_hwrng_present);
206 
207 long kvmppc_h_random(struct kvm_vcpu *vcpu)
208 {
209 	if (powernv_get_random_real_mode(&vcpu->arch.gpr[4]))
210 		return H_SUCCESS;
211 
212 	return H_HARDWARE;
213 }
214 
215 /*
216  * Send an interrupt or message to another CPU.
217  * The caller needs to include any barrier needed to order writes
218  * to memory vs. the IPI/message.
219  */
220 void kvmhv_rm_send_ipi(int cpu)
221 {
222 	void __iomem *xics_phys;
223 	unsigned long msg = PPC_DBELL_TYPE(PPC_DBELL_SERVER);
224 
225 	/* On POWER9 we can use msgsnd for any destination cpu. */
226 	if (cpu_has_feature(CPU_FTR_ARCH_300)) {
227 		msg |= get_hard_smp_processor_id(cpu);
228 		__asm__ __volatile__ (PPC_MSGSND(%0) : : "r" (msg));
229 		return;
230 	}
231 
232 	/* On POWER8 for IPIs to threads in the same core, use msgsnd. */
233 	if (cpu_has_feature(CPU_FTR_ARCH_207S) &&
234 	    cpu_first_thread_sibling(cpu) ==
235 	    cpu_first_thread_sibling(raw_smp_processor_id())) {
236 		msg |= cpu_thread_in_core(cpu);
237 		__asm__ __volatile__ (PPC_MSGSND(%0) : : "r" (msg));
238 		return;
239 	}
240 
241 	/* We should never reach this */
242 	if (WARN_ON_ONCE(xive_enabled()))
243 	    return;
244 
245 	/* Else poke the target with an IPI */
246 	xics_phys = paca[cpu].kvm_hstate.xics_phys;
247 	if (xics_phys)
248 		__raw_rm_writeb(IPI_PRIORITY, xics_phys + XICS_MFRR);
249 	else
250 		opal_int_set_mfrr(get_hard_smp_processor_id(cpu), IPI_PRIORITY);
251 }
252 
253 /*
254  * The following functions are called from the assembly code
255  * in book3s_hv_rmhandlers.S.
256  */
257 static void kvmhv_interrupt_vcore(struct kvmppc_vcore *vc, int active)
258 {
259 	int cpu = vc->pcpu;
260 
261 	/* Order setting of exit map vs. msgsnd/IPI */
262 	smp_mb();
263 	for (; active; active >>= 1, ++cpu)
264 		if (active & 1)
265 			kvmhv_rm_send_ipi(cpu);
266 }
267 
268 void kvmhv_commence_exit(int trap)
269 {
270 	struct kvmppc_vcore *vc = local_paca->kvm_hstate.kvm_vcore;
271 	int ptid = local_paca->kvm_hstate.ptid;
272 	struct kvm_split_mode *sip = local_paca->kvm_hstate.kvm_split_mode;
273 	int me, ee, i;
274 
275 	/* Set our bit in the threads-exiting-guest map in the 0xff00
276 	   bits of vcore->entry_exit_map */
277 	me = 0x100 << ptid;
278 	do {
279 		ee = vc->entry_exit_map;
280 	} while (cmpxchg(&vc->entry_exit_map, ee, ee | me) != ee);
281 
282 	/* Are we the first here? */
283 	if ((ee >> 8) != 0)
284 		return;
285 
286 	/*
287 	 * Trigger the other threads in this vcore to exit the guest.
288 	 * If this is a hypervisor decrementer interrupt then they
289 	 * will be already on their way out of the guest.
290 	 */
291 	if (trap != BOOK3S_INTERRUPT_HV_DECREMENTER)
292 		kvmhv_interrupt_vcore(vc, ee & ~(1 << ptid));
293 
294 	/*
295 	 * If we are doing dynamic micro-threading, interrupt the other
296 	 * subcores to pull them out of their guests too.
297 	 */
298 	if (!sip)
299 		return;
300 
301 	for (i = 0; i < MAX_SUBCORES; ++i) {
302 		vc = sip->master_vcs[i];
303 		if (!vc)
304 			break;
305 		do {
306 			ee = vc->entry_exit_map;
307 			/* Already asked to exit? */
308 			if ((ee >> 8) != 0)
309 				break;
310 		} while (cmpxchg(&vc->entry_exit_map, ee,
311 				 ee | VCORE_EXIT_REQ) != ee);
312 		if ((ee >> 8) == 0)
313 			kvmhv_interrupt_vcore(vc, ee);
314 	}
315 }
316 
317 struct kvmppc_host_rm_ops *kvmppc_host_rm_ops_hv;
318 EXPORT_SYMBOL_GPL(kvmppc_host_rm_ops_hv);
319 
320 #ifdef CONFIG_KVM_XICS
321 static struct kvmppc_irq_map *get_irqmap(struct kvmppc_passthru_irqmap *pimap,
322 					 u32 xisr)
323 {
324 	int i;
325 
326 	/*
327 	 * We access the mapped array here without a lock.  That
328 	 * is safe because we never reduce the number of entries
329 	 * in the array and we never change the v_hwirq field of
330 	 * an entry once it is set.
331 	 *
332 	 * We have also carefully ordered the stores in the writer
333 	 * and the loads here in the reader, so that if we find a matching
334 	 * hwirq here, the associated GSI and irq_desc fields are valid.
335 	 */
336 	for (i = 0; i < pimap->n_mapped; i++)  {
337 		if (xisr == pimap->mapped[i].r_hwirq) {
338 			/*
339 			 * Order subsequent reads in the caller to serialize
340 			 * with the writer.
341 			 */
342 			smp_rmb();
343 			return &pimap->mapped[i];
344 		}
345 	}
346 	return NULL;
347 }
348 
349 /*
350  * If we have an interrupt that's not an IPI, check if we have a
351  * passthrough adapter and if so, check if this external interrupt
352  * is for the adapter.
353  * We will attempt to deliver the IRQ directly to the target VCPU's
354  * ICP, the virtual ICP (based on affinity - the xive value in ICS).
355  *
356  * If the delivery fails or if this is not for a passthrough adapter,
357  * return to the host to handle this interrupt. We earlier
358  * saved a copy of the XIRR in the PACA, it will be picked up by
359  * the host ICP driver.
360  */
361 static int kvmppc_check_passthru(u32 xisr, __be32 xirr, bool *again)
362 {
363 	struct kvmppc_passthru_irqmap *pimap;
364 	struct kvmppc_irq_map *irq_map;
365 	struct kvm_vcpu *vcpu;
366 
367 	vcpu = local_paca->kvm_hstate.kvm_vcpu;
368 	if (!vcpu)
369 		return 1;
370 	pimap = kvmppc_get_passthru_irqmap(vcpu->kvm);
371 	if (!pimap)
372 		return 1;
373 	irq_map = get_irqmap(pimap, xisr);
374 	if (!irq_map)
375 		return 1;
376 
377 	/* We're handling this interrupt, generic code doesn't need to */
378 	local_paca->kvm_hstate.saved_xirr = 0;
379 
380 	return kvmppc_deliver_irq_passthru(vcpu, xirr, irq_map, pimap, again);
381 }
382 
383 #else
384 static inline int kvmppc_check_passthru(u32 xisr, __be32 xirr, bool *again)
385 {
386 	return 1;
387 }
388 #endif
389 
390 /*
391  * Determine what sort of external interrupt is pending (if any).
392  * Returns:
393  *	0 if no interrupt is pending
394  *	1 if an interrupt is pending that needs to be handled by the host
395  *	2 Passthrough that needs completion in the host
396  *	-1 if there was a guest wakeup IPI (which has now been cleared)
397  *	-2 if there is PCI passthrough external interrupt that was handled
398  */
399 static long kvmppc_read_one_intr(bool *again);
400 
401 long kvmppc_read_intr(void)
402 {
403 	long ret = 0;
404 	long rc;
405 	bool again;
406 
407 	if (xive_enabled())
408 		return 1;
409 
410 	do {
411 		again = false;
412 		rc = kvmppc_read_one_intr(&again);
413 		if (rc && (ret == 0 || rc > ret))
414 			ret = rc;
415 	} while (again);
416 	return ret;
417 }
418 
419 static long kvmppc_read_one_intr(bool *again)
420 {
421 	void __iomem *xics_phys;
422 	u32 h_xirr;
423 	__be32 xirr;
424 	u32 xisr;
425 	u8 host_ipi;
426 	int64_t rc;
427 
428 	if (xive_enabled())
429 		return 1;
430 
431 	/* see if a host IPI is pending */
432 	host_ipi = local_paca->kvm_hstate.host_ipi;
433 	if (host_ipi)
434 		return 1;
435 
436 	/* Now read the interrupt from the ICP */
437 	xics_phys = local_paca->kvm_hstate.xics_phys;
438 	rc = 0;
439 	if (!xics_phys)
440 		rc = opal_int_get_xirr(&xirr, false);
441 	else
442 		xirr = __raw_rm_readl(xics_phys + XICS_XIRR);
443 	if (rc < 0)
444 		return 1;
445 
446 	/*
447 	 * Save XIRR for later. Since we get control in reverse endian
448 	 * on LE systems, save it byte reversed and fetch it back in
449 	 * host endian. Note that xirr is the value read from the
450 	 * XIRR register, while h_xirr is the host endian version.
451 	 */
452 	h_xirr = be32_to_cpu(xirr);
453 	local_paca->kvm_hstate.saved_xirr = h_xirr;
454 	xisr = h_xirr & 0xffffff;
455 	/*
456 	 * Ensure that the store/load complete to guarantee all side
457 	 * effects of loading from XIRR has completed
458 	 */
459 	smp_mb();
460 
461 	/* if nothing pending in the ICP */
462 	if (!xisr)
463 		return 0;
464 
465 	/* We found something in the ICP...
466 	 *
467 	 * If it is an IPI, clear the MFRR and EOI it.
468 	 */
469 	if (xisr == XICS_IPI) {
470 		rc = 0;
471 		if (xics_phys) {
472 			__raw_rm_writeb(0xff, xics_phys + XICS_MFRR);
473 			__raw_rm_writel(xirr, xics_phys + XICS_XIRR);
474 		} else {
475 			opal_int_set_mfrr(hard_smp_processor_id(), 0xff);
476 			rc = opal_int_eoi(h_xirr);
477 		}
478 		/* If rc > 0, there is another interrupt pending */
479 		*again = rc > 0;
480 
481 		/*
482 		 * Need to ensure side effects of above stores
483 		 * complete before proceeding.
484 		 */
485 		smp_mb();
486 
487 		/*
488 		 * We need to re-check host IPI now in case it got set in the
489 		 * meantime. If it's clear, we bounce the interrupt to the
490 		 * guest
491 		 */
492 		host_ipi = local_paca->kvm_hstate.host_ipi;
493 		if (unlikely(host_ipi != 0)) {
494 			/* We raced with the host,
495 			 * we need to resend that IPI, bummer
496 			 */
497 			if (xics_phys)
498 				__raw_rm_writeb(IPI_PRIORITY,
499 						xics_phys + XICS_MFRR);
500 			else
501 				opal_int_set_mfrr(hard_smp_processor_id(),
502 						  IPI_PRIORITY);
503 			/* Let side effects complete */
504 			smp_mb();
505 			return 1;
506 		}
507 
508 		/* OK, it's an IPI for us */
509 		local_paca->kvm_hstate.saved_xirr = 0;
510 		return -1;
511 	}
512 
513 	return kvmppc_check_passthru(xisr, xirr, again);
514 }
515 
516 #ifdef CONFIG_KVM_XICS
517 static inline bool is_rm(void)
518 {
519 	return !(mfmsr() & MSR_DR);
520 }
521 
522 unsigned long kvmppc_rm_h_xirr(struct kvm_vcpu *vcpu)
523 {
524 	if (xive_enabled()) {
525 		if (is_rm())
526 			return xive_rm_h_xirr(vcpu);
527 		if (unlikely(!__xive_vm_h_xirr))
528 			return H_NOT_AVAILABLE;
529 		return __xive_vm_h_xirr(vcpu);
530 	} else
531 		return xics_rm_h_xirr(vcpu);
532 }
533 
534 unsigned long kvmppc_rm_h_xirr_x(struct kvm_vcpu *vcpu)
535 {
536 	vcpu->arch.gpr[5] = get_tb();
537 	if (xive_enabled()) {
538 		if (is_rm())
539 			return xive_rm_h_xirr(vcpu);
540 		if (unlikely(!__xive_vm_h_xirr))
541 			return H_NOT_AVAILABLE;
542 		return __xive_vm_h_xirr(vcpu);
543 	} else
544 		return xics_rm_h_xirr(vcpu);
545 }
546 
547 unsigned long kvmppc_rm_h_ipoll(struct kvm_vcpu *vcpu, unsigned long server)
548 {
549 	if (xive_enabled()) {
550 		if (is_rm())
551 			return xive_rm_h_ipoll(vcpu, server);
552 		if (unlikely(!__xive_vm_h_ipoll))
553 			return H_NOT_AVAILABLE;
554 		return __xive_vm_h_ipoll(vcpu, server);
555 	} else
556 		return H_TOO_HARD;
557 }
558 
559 int kvmppc_rm_h_ipi(struct kvm_vcpu *vcpu, unsigned long server,
560 		    unsigned long mfrr)
561 {
562 	if (xive_enabled()) {
563 		if (is_rm())
564 			return xive_rm_h_ipi(vcpu, server, mfrr);
565 		if (unlikely(!__xive_vm_h_ipi))
566 			return H_NOT_AVAILABLE;
567 		return __xive_vm_h_ipi(vcpu, server, mfrr);
568 	} else
569 		return xics_rm_h_ipi(vcpu, server, mfrr);
570 }
571 
572 int kvmppc_rm_h_cppr(struct kvm_vcpu *vcpu, unsigned long cppr)
573 {
574 	if (xive_enabled()) {
575 		if (is_rm())
576 			return xive_rm_h_cppr(vcpu, cppr);
577 		if (unlikely(!__xive_vm_h_cppr))
578 			return H_NOT_AVAILABLE;
579 		return __xive_vm_h_cppr(vcpu, cppr);
580 	} else
581 		return xics_rm_h_cppr(vcpu, cppr);
582 }
583 
584 int kvmppc_rm_h_eoi(struct kvm_vcpu *vcpu, unsigned long xirr)
585 {
586 	if (xive_enabled()) {
587 		if (is_rm())
588 			return xive_rm_h_eoi(vcpu, xirr);
589 		if (unlikely(!__xive_vm_h_eoi))
590 			return H_NOT_AVAILABLE;
591 		return __xive_vm_h_eoi(vcpu, xirr);
592 	} else
593 		return xics_rm_h_eoi(vcpu, xirr);
594 }
595 #endif /* CONFIG_KVM_XICS */
596