xref: /openbmc/linux/arch/powerpc/kvm/book3s_xive.c (revision d4fd6347)
1 /*
2  * Copyright 2017 Benjamin Herrenschmidt, IBM Corporation.
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 #define pr_fmt(fmt) "xive-kvm: " fmt
10 
11 #include <linux/kernel.h>
12 #include <linux/kvm_host.h>
13 #include <linux/err.h>
14 #include <linux/gfp.h>
15 #include <linux/spinlock.h>
16 #include <linux/delay.h>
17 #include <linux/percpu.h>
18 #include <linux/cpumask.h>
19 #include <linux/uaccess.h>
20 #include <asm/kvm_book3s.h>
21 #include <asm/kvm_ppc.h>
22 #include <asm/hvcall.h>
23 #include <asm/xics.h>
24 #include <asm/xive.h>
25 #include <asm/xive-regs.h>
26 #include <asm/debug.h>
27 #include <asm/debugfs.h>
28 #include <asm/time.h>
29 #include <asm/opal.h>
30 
31 #include <linux/debugfs.h>
32 #include <linux/seq_file.h>
33 
34 #include "book3s_xive.h"
35 
36 
37 /*
38  * Virtual mode variants of the hcalls for use on radix/radix
39  * with AIL. They require the VCPU's VP to be "pushed"
40  *
41  * We still instantiate them here because we use some of the
42  * generated utility functions as well in this file.
43  */
44 #define XIVE_RUNTIME_CHECKS
45 #define X_PFX xive_vm_
46 #define X_STATIC static
47 #define X_STAT_PFX stat_vm_
48 #define __x_tima		xive_tima
49 #define __x_eoi_page(xd)	((void __iomem *)((xd)->eoi_mmio))
50 #define __x_trig_page(xd)	((void __iomem *)((xd)->trig_mmio))
51 #define __x_writeb	__raw_writeb
52 #define __x_readw	__raw_readw
53 #define __x_readq	__raw_readq
54 #define __x_writeq	__raw_writeq
55 
56 #include "book3s_xive_template.c"
57 
58 /*
59  * We leave a gap of a couple of interrupts in the queue to
60  * account for the IPI and additional safety guard.
61  */
62 #define XIVE_Q_GAP	2
63 
64 /*
65  * Push a vcpu's context to the XIVE on guest entry.
66  * This assumes we are in virtual mode (MMU on)
67  */
68 void kvmppc_xive_push_vcpu(struct kvm_vcpu *vcpu)
69 {
70 	void __iomem *tima = local_paca->kvm_hstate.xive_tima_virt;
71 	u64 pq;
72 
73 	if (!tima)
74 		return;
75 	eieio();
76 	__raw_writeq(vcpu->arch.xive_saved_state.w01, tima + TM_QW1_OS);
77 	__raw_writel(vcpu->arch.xive_cam_word, tima + TM_QW1_OS + TM_WORD2);
78 	vcpu->arch.xive_pushed = 1;
79 	eieio();
80 
81 	/*
82 	 * We clear the irq_pending flag. There is a small chance of a
83 	 * race vs. the escalation interrupt happening on another
84 	 * processor setting it again, but the only consequence is to
85 	 * cause a spurious wakeup on the next H_CEDE, which is not an
86 	 * issue.
87 	 */
88 	vcpu->arch.irq_pending = 0;
89 
90 	/*
91 	 * In single escalation mode, if the escalation interrupt is
92 	 * on, we mask it.
93 	 */
94 	if (vcpu->arch.xive_esc_on) {
95 		pq = __raw_readq((void __iomem *)(vcpu->arch.xive_esc_vaddr +
96 						  XIVE_ESB_SET_PQ_01));
97 		mb();
98 
99 		/*
100 		 * We have a possible subtle race here: The escalation
101 		 * interrupt might have fired and be on its way to the
102 		 * host queue while we mask it, and if we unmask it
103 		 * early enough (re-cede right away), there is a
104 		 * theorical possibility that it fires again, thus
105 		 * landing in the target queue more than once which is
106 		 * a big no-no.
107 		 *
108 		 * Fortunately, solving this is rather easy. If the
109 		 * above load setting PQ to 01 returns a previous
110 		 * value where P is set, then we know the escalation
111 		 * interrupt is somewhere on its way to the host. In
112 		 * that case we simply don't clear the xive_esc_on
113 		 * flag below. It will be eventually cleared by the
114 		 * handler for the escalation interrupt.
115 		 *
116 		 * Then, when doing a cede, we check that flag again
117 		 * before re-enabling the escalation interrupt, and if
118 		 * set, we abort the cede.
119 		 */
120 		if (!(pq & XIVE_ESB_VAL_P))
121 			/* Now P is 0, we can clear the flag */
122 			vcpu->arch.xive_esc_on = 0;
123 	}
124 }
125 EXPORT_SYMBOL_GPL(kvmppc_xive_push_vcpu);
126 
127 /*
128  * This is a simple trigger for a generic XIVE IRQ. This must
129  * only be called for interrupts that support a trigger page
130  */
131 static bool xive_irq_trigger(struct xive_irq_data *xd)
132 {
133 	/* This should be only for MSIs */
134 	if (WARN_ON(xd->flags & XIVE_IRQ_FLAG_LSI))
135 		return false;
136 
137 	/* Those interrupts should always have a trigger page */
138 	if (WARN_ON(!xd->trig_mmio))
139 		return false;
140 
141 	out_be64(xd->trig_mmio, 0);
142 
143 	return true;
144 }
145 
146 static irqreturn_t xive_esc_irq(int irq, void *data)
147 {
148 	struct kvm_vcpu *vcpu = data;
149 
150 	vcpu->arch.irq_pending = 1;
151 	smp_mb();
152 	if (vcpu->arch.ceded)
153 		kvmppc_fast_vcpu_kick(vcpu);
154 
155 	/* Since we have the no-EOI flag, the interrupt is effectively
156 	 * disabled now. Clearing xive_esc_on means we won't bother
157 	 * doing so on the next entry.
158 	 *
159 	 * This also allows the entry code to know that if a PQ combination
160 	 * of 10 is observed while xive_esc_on is true, it means the queue
161 	 * contains an unprocessed escalation interrupt. We don't make use of
162 	 * that knowledge today but might (see comment in book3s_hv_rmhandler.S)
163 	 */
164 	vcpu->arch.xive_esc_on = false;
165 
166 	return IRQ_HANDLED;
167 }
168 
169 int kvmppc_xive_attach_escalation(struct kvm_vcpu *vcpu, u8 prio,
170 				  bool single_escalation)
171 {
172 	struct kvmppc_xive_vcpu *xc = vcpu->arch.xive_vcpu;
173 	struct xive_q *q = &xc->queues[prio];
174 	char *name = NULL;
175 	int rc;
176 
177 	/* Already there ? */
178 	if (xc->esc_virq[prio])
179 		return 0;
180 
181 	/* Hook up the escalation interrupt */
182 	xc->esc_virq[prio] = irq_create_mapping(NULL, q->esc_irq);
183 	if (!xc->esc_virq[prio]) {
184 		pr_err("Failed to map escalation interrupt for queue %d of VCPU %d\n",
185 		       prio, xc->server_num);
186 		return -EIO;
187 	}
188 
189 	if (single_escalation)
190 		name = kasprintf(GFP_KERNEL, "kvm-%d-%d",
191 				 vcpu->kvm->arch.lpid, xc->server_num);
192 	else
193 		name = kasprintf(GFP_KERNEL, "kvm-%d-%d-%d",
194 				 vcpu->kvm->arch.lpid, xc->server_num, prio);
195 	if (!name) {
196 		pr_err("Failed to allocate escalation irq name for queue %d of VCPU %d\n",
197 		       prio, xc->server_num);
198 		rc = -ENOMEM;
199 		goto error;
200 	}
201 
202 	pr_devel("Escalation %s irq %d (prio %d)\n", name, xc->esc_virq[prio], prio);
203 
204 	rc = request_irq(xc->esc_virq[prio], xive_esc_irq,
205 			 IRQF_NO_THREAD, name, vcpu);
206 	if (rc) {
207 		pr_err("Failed to request escalation interrupt for queue %d of VCPU %d\n",
208 		       prio, xc->server_num);
209 		goto error;
210 	}
211 	xc->esc_virq_names[prio] = name;
212 
213 	/* In single escalation mode, we grab the ESB MMIO of the
214 	 * interrupt and mask it. Also populate the VCPU v/raddr
215 	 * of the ESB page for use by asm entry/exit code. Finally
216 	 * set the XIVE_IRQ_NO_EOI flag which will prevent the
217 	 * core code from performing an EOI on the escalation
218 	 * interrupt, thus leaving it effectively masked after
219 	 * it fires once.
220 	 */
221 	if (single_escalation) {
222 		struct irq_data *d = irq_get_irq_data(xc->esc_virq[prio]);
223 		struct xive_irq_data *xd = irq_data_get_irq_handler_data(d);
224 
225 		xive_vm_esb_load(xd, XIVE_ESB_SET_PQ_01);
226 		vcpu->arch.xive_esc_raddr = xd->eoi_page;
227 		vcpu->arch.xive_esc_vaddr = (__force u64)xd->eoi_mmio;
228 		xd->flags |= XIVE_IRQ_NO_EOI;
229 	}
230 
231 	return 0;
232 error:
233 	irq_dispose_mapping(xc->esc_virq[prio]);
234 	xc->esc_virq[prio] = 0;
235 	kfree(name);
236 	return rc;
237 }
238 
239 static int xive_provision_queue(struct kvm_vcpu *vcpu, u8 prio)
240 {
241 	struct kvmppc_xive_vcpu *xc = vcpu->arch.xive_vcpu;
242 	struct kvmppc_xive *xive = xc->xive;
243 	struct xive_q *q =  &xc->queues[prio];
244 	void *qpage;
245 	int rc;
246 
247 	if (WARN_ON(q->qpage))
248 		return 0;
249 
250 	/* Allocate the queue and retrieve infos on current node for now */
251 	qpage = (__be32 *)__get_free_pages(GFP_KERNEL, xive->q_page_order);
252 	if (!qpage) {
253 		pr_err("Failed to allocate queue %d for VCPU %d\n",
254 		       prio, xc->server_num);
255 		return -ENOMEM;
256 	}
257 	memset(qpage, 0, 1 << xive->q_order);
258 
259 	/*
260 	 * Reconfigure the queue. This will set q->qpage only once the
261 	 * queue is fully configured. This is a requirement for prio 0
262 	 * as we will stop doing EOIs for every IPI as soon as we observe
263 	 * qpage being non-NULL, and instead will only EOI when we receive
264 	 * corresponding queue 0 entries
265 	 */
266 	rc = xive_native_configure_queue(xc->vp_id, q, prio, qpage,
267 					 xive->q_order, true);
268 	if (rc)
269 		pr_err("Failed to configure queue %d for VCPU %d\n",
270 		       prio, xc->server_num);
271 	return rc;
272 }
273 
274 /* Called with kvm_lock held */
275 static int xive_check_provisioning(struct kvm *kvm, u8 prio)
276 {
277 	struct kvmppc_xive *xive = kvm->arch.xive;
278 	struct kvm_vcpu *vcpu;
279 	int i, rc;
280 
281 	lockdep_assert_held(&kvm->lock);
282 
283 	/* Already provisioned ? */
284 	if (xive->qmap & (1 << prio))
285 		return 0;
286 
287 	pr_devel("Provisioning prio... %d\n", prio);
288 
289 	/* Provision each VCPU and enable escalations if needed */
290 	kvm_for_each_vcpu(i, vcpu, kvm) {
291 		if (!vcpu->arch.xive_vcpu)
292 			continue;
293 		rc = xive_provision_queue(vcpu, prio);
294 		if (rc == 0 && !xive->single_escalation)
295 			kvmppc_xive_attach_escalation(vcpu, prio,
296 						      xive->single_escalation);
297 		if (rc)
298 			return rc;
299 	}
300 
301 	/* Order previous stores and mark it as provisioned */
302 	mb();
303 	xive->qmap |= (1 << prio);
304 	return 0;
305 }
306 
307 static void xive_inc_q_pending(struct kvm *kvm, u32 server, u8 prio)
308 {
309 	struct kvm_vcpu *vcpu;
310 	struct kvmppc_xive_vcpu *xc;
311 	struct xive_q *q;
312 
313 	/* Locate target server */
314 	vcpu = kvmppc_xive_find_server(kvm, server);
315 	if (!vcpu) {
316 		pr_warn("%s: Can't find server %d\n", __func__, server);
317 		return;
318 	}
319 	xc = vcpu->arch.xive_vcpu;
320 	if (WARN_ON(!xc))
321 		return;
322 
323 	q = &xc->queues[prio];
324 	atomic_inc(&q->pending_count);
325 }
326 
327 static int xive_try_pick_queue(struct kvm_vcpu *vcpu, u8 prio)
328 {
329 	struct kvmppc_xive_vcpu *xc = vcpu->arch.xive_vcpu;
330 	struct xive_q *q;
331 	u32 max;
332 
333 	if (WARN_ON(!xc))
334 		return -ENXIO;
335 	if (!xc->valid)
336 		return -ENXIO;
337 
338 	q = &xc->queues[prio];
339 	if (WARN_ON(!q->qpage))
340 		return -ENXIO;
341 
342 	/* Calculate max number of interrupts in that queue. */
343 	max = (q->msk + 1) - XIVE_Q_GAP;
344 	return atomic_add_unless(&q->count, 1, max) ? 0 : -EBUSY;
345 }
346 
347 int kvmppc_xive_select_target(struct kvm *kvm, u32 *server, u8 prio)
348 {
349 	struct kvm_vcpu *vcpu;
350 	int i, rc;
351 
352 	/* Locate target server */
353 	vcpu = kvmppc_xive_find_server(kvm, *server);
354 	if (!vcpu) {
355 		pr_devel("Can't find server %d\n", *server);
356 		return -EINVAL;
357 	}
358 
359 	pr_devel("Finding irq target on 0x%x/%d...\n", *server, prio);
360 
361 	/* Try pick it */
362 	rc = xive_try_pick_queue(vcpu, prio);
363 	if (rc == 0)
364 		return rc;
365 
366 	pr_devel(" .. failed, looking up candidate...\n");
367 
368 	/* Failed, pick another VCPU */
369 	kvm_for_each_vcpu(i, vcpu, kvm) {
370 		if (!vcpu->arch.xive_vcpu)
371 			continue;
372 		rc = xive_try_pick_queue(vcpu, prio);
373 		if (rc == 0) {
374 			*server = vcpu->arch.xive_vcpu->server_num;
375 			pr_devel("  found on 0x%x/%d\n", *server, prio);
376 			return rc;
377 		}
378 	}
379 	pr_devel("  no available target !\n");
380 
381 	/* No available target ! */
382 	return -EBUSY;
383 }
384 
385 static u8 xive_lock_and_mask(struct kvmppc_xive *xive,
386 			     struct kvmppc_xive_src_block *sb,
387 			     struct kvmppc_xive_irq_state *state)
388 {
389 	struct xive_irq_data *xd;
390 	u32 hw_num;
391 	u8 old_prio;
392 	u64 val;
393 
394 	/*
395 	 * Take the lock, set masked, try again if racing
396 	 * with H_EOI
397 	 */
398 	for (;;) {
399 		arch_spin_lock(&sb->lock);
400 		old_prio = state->guest_priority;
401 		state->guest_priority = MASKED;
402 		mb();
403 		if (!state->in_eoi)
404 			break;
405 		state->guest_priority = old_prio;
406 		arch_spin_unlock(&sb->lock);
407 	}
408 
409 	/* No change ? Bail */
410 	if (old_prio == MASKED)
411 		return old_prio;
412 
413 	/* Get the right irq */
414 	kvmppc_xive_select_irq(state, &hw_num, &xd);
415 
416 	/*
417 	 * If the interrupt is marked as needing masking via
418 	 * firmware, we do it here. Firmware masking however
419 	 * is "lossy", it won't return the old p and q bits
420 	 * and won't set the interrupt to a state where it will
421 	 * record queued ones. If this is an issue we should do
422 	 * lazy masking instead.
423 	 *
424 	 * For now, we work around this in unmask by forcing
425 	 * an interrupt whenever we unmask a non-LSI via FW
426 	 * (if ever).
427 	 */
428 	if (xd->flags & OPAL_XIVE_IRQ_MASK_VIA_FW) {
429 		xive_native_configure_irq(hw_num,
430 				kvmppc_xive_vp(xive, state->act_server),
431 				MASKED, state->number);
432 		/* set old_p so we can track if an H_EOI was done */
433 		state->old_p = true;
434 		state->old_q = false;
435 	} else {
436 		/* Set PQ to 10, return old P and old Q and remember them */
437 		val = xive_vm_esb_load(xd, XIVE_ESB_SET_PQ_10);
438 		state->old_p = !!(val & 2);
439 		state->old_q = !!(val & 1);
440 
441 		/*
442 		 * Synchronize hardware to sensure the queues are updated
443 		 * when masking
444 		 */
445 		xive_native_sync_source(hw_num);
446 	}
447 
448 	return old_prio;
449 }
450 
451 static void xive_lock_for_unmask(struct kvmppc_xive_src_block *sb,
452 				 struct kvmppc_xive_irq_state *state)
453 {
454 	/*
455 	 * Take the lock try again if racing with H_EOI
456 	 */
457 	for (;;) {
458 		arch_spin_lock(&sb->lock);
459 		if (!state->in_eoi)
460 			break;
461 		arch_spin_unlock(&sb->lock);
462 	}
463 }
464 
465 static void xive_finish_unmask(struct kvmppc_xive *xive,
466 			       struct kvmppc_xive_src_block *sb,
467 			       struct kvmppc_xive_irq_state *state,
468 			       u8 prio)
469 {
470 	struct xive_irq_data *xd;
471 	u32 hw_num;
472 
473 	/* If we aren't changing a thing, move on */
474 	if (state->guest_priority != MASKED)
475 		goto bail;
476 
477 	/* Get the right irq */
478 	kvmppc_xive_select_irq(state, &hw_num, &xd);
479 
480 	/*
481 	 * See command in xive_lock_and_mask() concerning masking
482 	 * via firmware.
483 	 */
484 	if (xd->flags & OPAL_XIVE_IRQ_MASK_VIA_FW) {
485 		xive_native_configure_irq(hw_num,
486 				kvmppc_xive_vp(xive, state->act_server),
487 				state->act_priority, state->number);
488 		/* If an EOI is needed, do it here */
489 		if (!state->old_p)
490 			xive_vm_source_eoi(hw_num, xd);
491 		/* If this is not an LSI, force a trigger */
492 		if (!(xd->flags & OPAL_XIVE_IRQ_LSI))
493 			xive_irq_trigger(xd);
494 		goto bail;
495 	}
496 
497 	/* Old Q set, set PQ to 11 */
498 	if (state->old_q)
499 		xive_vm_esb_load(xd, XIVE_ESB_SET_PQ_11);
500 
501 	/*
502 	 * If not old P, then perform an "effective" EOI,
503 	 * on the source. This will handle the cases where
504 	 * FW EOI is needed.
505 	 */
506 	if (!state->old_p)
507 		xive_vm_source_eoi(hw_num, xd);
508 
509 	/* Synchronize ordering and mark unmasked */
510 	mb();
511 bail:
512 	state->guest_priority = prio;
513 }
514 
515 /*
516  * Target an interrupt to a given server/prio, this will fallback
517  * to another server if necessary and perform the HW targetting
518  * updates as needed
519  *
520  * NOTE: Must be called with the state lock held
521  */
522 static int xive_target_interrupt(struct kvm *kvm,
523 				 struct kvmppc_xive_irq_state *state,
524 				 u32 server, u8 prio)
525 {
526 	struct kvmppc_xive *xive = kvm->arch.xive;
527 	u32 hw_num;
528 	int rc;
529 
530 	/*
531 	 * This will return a tentative server and actual
532 	 * priority. The count for that new target will have
533 	 * already been incremented.
534 	 */
535 	rc = kvmppc_xive_select_target(kvm, &server, prio);
536 
537 	/*
538 	 * We failed to find a target ? Not much we can do
539 	 * at least until we support the GIQ.
540 	 */
541 	if (rc)
542 		return rc;
543 
544 	/*
545 	 * Increment the old queue pending count if there
546 	 * was one so that the old queue count gets adjusted later
547 	 * when observed to be empty.
548 	 */
549 	if (state->act_priority != MASKED)
550 		xive_inc_q_pending(kvm,
551 				   state->act_server,
552 				   state->act_priority);
553 	/*
554 	 * Update state and HW
555 	 */
556 	state->act_priority = prio;
557 	state->act_server = server;
558 
559 	/* Get the right irq */
560 	kvmppc_xive_select_irq(state, &hw_num, NULL);
561 
562 	return xive_native_configure_irq(hw_num,
563 					 kvmppc_xive_vp(xive, server),
564 					 prio, state->number);
565 }
566 
567 /*
568  * Targetting rules: In order to avoid losing track of
569  * pending interrupts accross mask and unmask, which would
570  * allow queue overflows, we implement the following rules:
571  *
572  *  - Unless it was never enabled (or we run out of capacity)
573  *    an interrupt is always targetted at a valid server/queue
574  *    pair even when "masked" by the guest. This pair tends to
575  *    be the last one used but it can be changed under some
576  *    circumstances. That allows us to separate targetting
577  *    from masking, we only handle accounting during (re)targetting,
578  *    this also allows us to let an interrupt drain into its target
579  *    queue after masking, avoiding complex schemes to remove
580  *    interrupts out of remote processor queues.
581  *
582  *  - When masking, we set PQ to 10 and save the previous value
583  *    of P and Q.
584  *
585  *  - When unmasking, if saved Q was set, we set PQ to 11
586  *    otherwise we leave PQ to the HW state which will be either
587  *    10 if nothing happened or 11 if the interrupt fired while
588  *    masked. Effectively we are OR'ing the previous Q into the
589  *    HW Q.
590  *
591  *    Then if saved P is clear, we do an effective EOI (Q->P->Trigger)
592  *    which will unmask the interrupt and shoot a new one if Q was
593  *    set.
594  *
595  *    Otherwise (saved P is set) we leave PQ unchanged (so 10 or 11,
596  *    effectively meaning an H_EOI from the guest is still expected
597  *    for that interrupt).
598  *
599  *  - If H_EOI occurs while masked, we clear the saved P.
600  *
601  *  - When changing target, we account on the new target and
602  *    increment a separate "pending" counter on the old one.
603  *    This pending counter will be used to decrement the old
604  *    target's count when its queue has been observed empty.
605  */
606 
607 int kvmppc_xive_set_xive(struct kvm *kvm, u32 irq, u32 server,
608 			 u32 priority)
609 {
610 	struct kvmppc_xive *xive = kvm->arch.xive;
611 	struct kvmppc_xive_src_block *sb;
612 	struct kvmppc_xive_irq_state *state;
613 	u8 new_act_prio;
614 	int rc = 0;
615 	u16 idx;
616 
617 	if (!xive)
618 		return -ENODEV;
619 
620 	pr_devel("set_xive ! irq 0x%x server 0x%x prio %d\n",
621 		 irq, server, priority);
622 
623 	/* First, check provisioning of queues */
624 	if (priority != MASKED)
625 		rc = xive_check_provisioning(xive->kvm,
626 			      xive_prio_from_guest(priority));
627 	if (rc) {
628 		pr_devel("  provisioning failure %d !\n", rc);
629 		return rc;
630 	}
631 
632 	sb = kvmppc_xive_find_source(xive, irq, &idx);
633 	if (!sb)
634 		return -EINVAL;
635 	state = &sb->irq_state[idx];
636 
637 	/*
638 	 * We first handle masking/unmasking since the locking
639 	 * might need to be retried due to EOIs, we'll handle
640 	 * targetting changes later. These functions will return
641 	 * with the SB lock held.
642 	 *
643 	 * xive_lock_and_mask() will also set state->guest_priority
644 	 * but won't otherwise change other fields of the state.
645 	 *
646 	 * xive_lock_for_unmask will not actually unmask, this will
647 	 * be done later by xive_finish_unmask() once the targetting
648 	 * has been done, so we don't try to unmask an interrupt
649 	 * that hasn't yet been targetted.
650 	 */
651 	if (priority == MASKED)
652 		xive_lock_and_mask(xive, sb, state);
653 	else
654 		xive_lock_for_unmask(sb, state);
655 
656 
657 	/*
658 	 * Then we handle targetting.
659 	 *
660 	 * First calculate a new "actual priority"
661 	 */
662 	new_act_prio = state->act_priority;
663 	if (priority != MASKED)
664 		new_act_prio = xive_prio_from_guest(priority);
665 
666 	pr_devel(" new_act_prio=%x act_server=%x act_prio=%x\n",
667 		 new_act_prio, state->act_server, state->act_priority);
668 
669 	/*
670 	 * Then check if we actually need to change anything,
671 	 *
672 	 * The condition for re-targetting the interrupt is that
673 	 * we have a valid new priority (new_act_prio is not 0xff)
674 	 * and either the server or the priority changed.
675 	 *
676 	 * Note: If act_priority was ff and the new priority is
677 	 *       also ff, we don't do anything and leave the interrupt
678 	 *       untargetted. An attempt of doing an int_on on an
679 	 *       untargetted interrupt will fail. If that is a problem
680 	 *       we could initialize interrupts with valid default
681 	 */
682 
683 	if (new_act_prio != MASKED &&
684 	    (state->act_server != server ||
685 	     state->act_priority != new_act_prio))
686 		rc = xive_target_interrupt(kvm, state, server, new_act_prio);
687 
688 	/*
689 	 * Perform the final unmasking of the interrupt source
690 	 * if necessary
691 	 */
692 	if (priority != MASKED)
693 		xive_finish_unmask(xive, sb, state, priority);
694 
695 	/*
696 	 * Finally Update saved_priority to match. Only int_on/off
697 	 * set this field to a different value.
698 	 */
699 	state->saved_priority = priority;
700 
701 	arch_spin_unlock(&sb->lock);
702 	return rc;
703 }
704 
705 int kvmppc_xive_get_xive(struct kvm *kvm, u32 irq, u32 *server,
706 			 u32 *priority)
707 {
708 	struct kvmppc_xive *xive = kvm->arch.xive;
709 	struct kvmppc_xive_src_block *sb;
710 	struct kvmppc_xive_irq_state *state;
711 	u16 idx;
712 
713 	if (!xive)
714 		return -ENODEV;
715 
716 	sb = kvmppc_xive_find_source(xive, irq, &idx);
717 	if (!sb)
718 		return -EINVAL;
719 	state = &sb->irq_state[idx];
720 	arch_spin_lock(&sb->lock);
721 	*server = state->act_server;
722 	*priority = state->guest_priority;
723 	arch_spin_unlock(&sb->lock);
724 
725 	return 0;
726 }
727 
728 int kvmppc_xive_int_on(struct kvm *kvm, u32 irq)
729 {
730 	struct kvmppc_xive *xive = kvm->arch.xive;
731 	struct kvmppc_xive_src_block *sb;
732 	struct kvmppc_xive_irq_state *state;
733 	u16 idx;
734 
735 	if (!xive)
736 		return -ENODEV;
737 
738 	sb = kvmppc_xive_find_source(xive, irq, &idx);
739 	if (!sb)
740 		return -EINVAL;
741 	state = &sb->irq_state[idx];
742 
743 	pr_devel("int_on(irq=0x%x)\n", irq);
744 
745 	/*
746 	 * Check if interrupt was not targetted
747 	 */
748 	if (state->act_priority == MASKED) {
749 		pr_devel("int_on on untargetted interrupt\n");
750 		return -EINVAL;
751 	}
752 
753 	/* If saved_priority is 0xff, do nothing */
754 	if (state->saved_priority == MASKED)
755 		return 0;
756 
757 	/*
758 	 * Lock and unmask it.
759 	 */
760 	xive_lock_for_unmask(sb, state);
761 	xive_finish_unmask(xive, sb, state, state->saved_priority);
762 	arch_spin_unlock(&sb->lock);
763 
764 	return 0;
765 }
766 
767 int kvmppc_xive_int_off(struct kvm *kvm, u32 irq)
768 {
769 	struct kvmppc_xive *xive = kvm->arch.xive;
770 	struct kvmppc_xive_src_block *sb;
771 	struct kvmppc_xive_irq_state *state;
772 	u16 idx;
773 
774 	if (!xive)
775 		return -ENODEV;
776 
777 	sb = kvmppc_xive_find_source(xive, irq, &idx);
778 	if (!sb)
779 		return -EINVAL;
780 	state = &sb->irq_state[idx];
781 
782 	pr_devel("int_off(irq=0x%x)\n", irq);
783 
784 	/*
785 	 * Lock and mask
786 	 */
787 	state->saved_priority = xive_lock_and_mask(xive, sb, state);
788 	arch_spin_unlock(&sb->lock);
789 
790 	return 0;
791 }
792 
793 static bool xive_restore_pending_irq(struct kvmppc_xive *xive, u32 irq)
794 {
795 	struct kvmppc_xive_src_block *sb;
796 	struct kvmppc_xive_irq_state *state;
797 	u16 idx;
798 
799 	sb = kvmppc_xive_find_source(xive, irq, &idx);
800 	if (!sb)
801 		return false;
802 	state = &sb->irq_state[idx];
803 	if (!state->valid)
804 		return false;
805 
806 	/*
807 	 * Trigger the IPI. This assumes we never restore a pass-through
808 	 * interrupt which should be safe enough
809 	 */
810 	xive_irq_trigger(&state->ipi_data);
811 
812 	return true;
813 }
814 
815 u64 kvmppc_xive_get_icp(struct kvm_vcpu *vcpu)
816 {
817 	struct kvmppc_xive_vcpu *xc = vcpu->arch.xive_vcpu;
818 
819 	if (!xc)
820 		return 0;
821 
822 	/* Return the per-cpu state for state saving/migration */
823 	return (u64)xc->cppr << KVM_REG_PPC_ICP_CPPR_SHIFT |
824 	       (u64)xc->mfrr << KVM_REG_PPC_ICP_MFRR_SHIFT |
825 	       (u64)0xff << KVM_REG_PPC_ICP_PPRI_SHIFT;
826 }
827 
828 int kvmppc_xive_set_icp(struct kvm_vcpu *vcpu, u64 icpval)
829 {
830 	struct kvmppc_xive_vcpu *xc = vcpu->arch.xive_vcpu;
831 	struct kvmppc_xive *xive = vcpu->kvm->arch.xive;
832 	u8 cppr, mfrr;
833 	u32 xisr;
834 
835 	if (!xc || !xive)
836 		return -ENOENT;
837 
838 	/* Grab individual state fields. We don't use pending_pri */
839 	cppr = icpval >> KVM_REG_PPC_ICP_CPPR_SHIFT;
840 	xisr = (icpval >> KVM_REG_PPC_ICP_XISR_SHIFT) &
841 		KVM_REG_PPC_ICP_XISR_MASK;
842 	mfrr = icpval >> KVM_REG_PPC_ICP_MFRR_SHIFT;
843 
844 	pr_devel("set_icp vcpu %d cppr=0x%x mfrr=0x%x xisr=0x%x\n",
845 		 xc->server_num, cppr, mfrr, xisr);
846 
847 	/*
848 	 * We can't update the state of a "pushed" VCPU, but that
849 	 * shouldn't happen because the vcpu->mutex makes running a
850 	 * vcpu mutually exclusive with doing one_reg get/set on it.
851 	 */
852 	if (WARN_ON(vcpu->arch.xive_pushed))
853 		return -EIO;
854 
855 	/* Update VCPU HW saved state */
856 	vcpu->arch.xive_saved_state.cppr = cppr;
857 	xc->hw_cppr = xc->cppr = cppr;
858 
859 	/*
860 	 * Update MFRR state. If it's not 0xff, we mark the VCPU as
861 	 * having a pending MFRR change, which will re-evaluate the
862 	 * target. The VCPU will thus potentially get a spurious
863 	 * interrupt but that's not a big deal.
864 	 */
865 	xc->mfrr = mfrr;
866 	if (mfrr < cppr)
867 		xive_irq_trigger(&xc->vp_ipi_data);
868 
869 	/*
870 	 * Now saved XIRR is "interesting". It means there's something in
871 	 * the legacy "1 element" queue... for an IPI we simply ignore it,
872 	 * as the MFRR restore will handle that. For anything else we need
873 	 * to force a resend of the source.
874 	 * However the source may not have been setup yet. If that's the
875 	 * case, we keep that info and increment a counter in the xive to
876 	 * tell subsequent xive_set_source() to go look.
877 	 */
878 	if (xisr > XICS_IPI && !xive_restore_pending_irq(xive, xisr)) {
879 		xc->delayed_irq = xisr;
880 		xive->delayed_irqs++;
881 		pr_devel("  xisr restore delayed\n");
882 	}
883 
884 	return 0;
885 }
886 
887 int kvmppc_xive_set_mapped(struct kvm *kvm, unsigned long guest_irq,
888 			   struct irq_desc *host_desc)
889 {
890 	struct kvmppc_xive *xive = kvm->arch.xive;
891 	struct kvmppc_xive_src_block *sb;
892 	struct kvmppc_xive_irq_state *state;
893 	struct irq_data *host_data = irq_desc_get_irq_data(host_desc);
894 	unsigned int host_irq = irq_desc_get_irq(host_desc);
895 	unsigned int hw_irq = (unsigned int)irqd_to_hwirq(host_data);
896 	u16 idx;
897 	u8 prio;
898 	int rc;
899 
900 	if (!xive)
901 		return -ENODEV;
902 
903 	pr_devel("set_mapped girq 0x%lx host HW irq 0x%x...\n",guest_irq, hw_irq);
904 
905 	sb = kvmppc_xive_find_source(xive, guest_irq, &idx);
906 	if (!sb)
907 		return -EINVAL;
908 	state = &sb->irq_state[idx];
909 
910 	/*
911 	 * Mark the passed-through interrupt as going to a VCPU,
912 	 * this will prevent further EOIs and similar operations
913 	 * from the XIVE code. It will also mask the interrupt
914 	 * to either PQ=10 or 11 state, the latter if the interrupt
915 	 * is pending. This will allow us to unmask or retrigger it
916 	 * after routing it to the guest with a simple EOI.
917 	 *
918 	 * The "state" argument is a "token", all it needs is to be
919 	 * non-NULL to switch to passed-through or NULL for the
920 	 * other way around. We may not yet have an actual VCPU
921 	 * target here and we don't really care.
922 	 */
923 	rc = irq_set_vcpu_affinity(host_irq, state);
924 	if (rc) {
925 		pr_err("Failed to set VCPU affinity for irq %d\n", host_irq);
926 		return rc;
927 	}
928 
929 	/*
930 	 * Mask and read state of IPI. We need to know if its P bit
931 	 * is set as that means it's potentially already using a
932 	 * queue entry in the target
933 	 */
934 	prio = xive_lock_and_mask(xive, sb, state);
935 	pr_devel(" old IPI prio %02x P:%d Q:%d\n", prio,
936 		 state->old_p, state->old_q);
937 
938 	/* Turn the IPI hard off */
939 	xive_vm_esb_load(&state->ipi_data, XIVE_ESB_SET_PQ_01);
940 
941 	/*
942 	 * Reset ESB guest mapping. Needed when ESB pages are exposed
943 	 * to the guest in XIVE native mode
944 	 */
945 	if (xive->ops && xive->ops->reset_mapped)
946 		xive->ops->reset_mapped(kvm, guest_irq);
947 
948 	/* Grab info about irq */
949 	state->pt_number = hw_irq;
950 	state->pt_data = irq_data_get_irq_handler_data(host_data);
951 
952 	/*
953 	 * Configure the IRQ to match the existing configuration of
954 	 * the IPI if it was already targetted. Otherwise this will
955 	 * mask the interrupt in a lossy way (act_priority is 0xff)
956 	 * which is fine for a never started interrupt.
957 	 */
958 	xive_native_configure_irq(hw_irq,
959 				  kvmppc_xive_vp(xive, state->act_server),
960 				  state->act_priority, state->number);
961 
962 	/*
963 	 * We do an EOI to enable the interrupt (and retrigger if needed)
964 	 * if the guest has the interrupt unmasked and the P bit was *not*
965 	 * set in the IPI. If it was set, we know a slot may still be in
966 	 * use in the target queue thus we have to wait for a guest
967 	 * originated EOI
968 	 */
969 	if (prio != MASKED && !state->old_p)
970 		xive_vm_source_eoi(hw_irq, state->pt_data);
971 
972 	/* Clear old_p/old_q as they are no longer relevant */
973 	state->old_p = state->old_q = false;
974 
975 	/* Restore guest prio (unlocks EOI) */
976 	mb();
977 	state->guest_priority = prio;
978 	arch_spin_unlock(&sb->lock);
979 
980 	return 0;
981 }
982 EXPORT_SYMBOL_GPL(kvmppc_xive_set_mapped);
983 
984 int kvmppc_xive_clr_mapped(struct kvm *kvm, unsigned long guest_irq,
985 			   struct irq_desc *host_desc)
986 {
987 	struct kvmppc_xive *xive = kvm->arch.xive;
988 	struct kvmppc_xive_src_block *sb;
989 	struct kvmppc_xive_irq_state *state;
990 	unsigned int host_irq = irq_desc_get_irq(host_desc);
991 	u16 idx;
992 	u8 prio;
993 	int rc;
994 
995 	if (!xive)
996 		return -ENODEV;
997 
998 	pr_devel("clr_mapped girq 0x%lx...\n", guest_irq);
999 
1000 	sb = kvmppc_xive_find_source(xive, guest_irq, &idx);
1001 	if (!sb)
1002 		return -EINVAL;
1003 	state = &sb->irq_state[idx];
1004 
1005 	/*
1006 	 * Mask and read state of IRQ. We need to know if its P bit
1007 	 * is set as that means it's potentially already using a
1008 	 * queue entry in the target
1009 	 */
1010 	prio = xive_lock_and_mask(xive, sb, state);
1011 	pr_devel(" old IRQ prio %02x P:%d Q:%d\n", prio,
1012 		 state->old_p, state->old_q);
1013 
1014 	/*
1015 	 * If old_p is set, the interrupt is pending, we switch it to
1016 	 * PQ=11. This will force a resend in the host so the interrupt
1017 	 * isn't lost to whatver host driver may pick it up
1018 	 */
1019 	if (state->old_p)
1020 		xive_vm_esb_load(state->pt_data, XIVE_ESB_SET_PQ_11);
1021 
1022 	/* Release the passed-through interrupt to the host */
1023 	rc = irq_set_vcpu_affinity(host_irq, NULL);
1024 	if (rc) {
1025 		pr_err("Failed to clr VCPU affinity for irq %d\n", host_irq);
1026 		return rc;
1027 	}
1028 
1029 	/* Forget about the IRQ */
1030 	state->pt_number = 0;
1031 	state->pt_data = NULL;
1032 
1033 	/*
1034 	 * Reset ESB guest mapping. Needed when ESB pages are exposed
1035 	 * to the guest in XIVE native mode
1036 	 */
1037 	if (xive->ops && xive->ops->reset_mapped) {
1038 		xive->ops->reset_mapped(kvm, guest_irq);
1039 	}
1040 
1041 	/* Reconfigure the IPI */
1042 	xive_native_configure_irq(state->ipi_number,
1043 				  kvmppc_xive_vp(xive, state->act_server),
1044 				  state->act_priority, state->number);
1045 
1046 	/*
1047 	 * If old_p is set (we have a queue entry potentially
1048 	 * occupied) or the interrupt is masked, we set the IPI
1049 	 * to PQ=10 state. Otherwise we just re-enable it (PQ=00).
1050 	 */
1051 	if (prio == MASKED || state->old_p)
1052 		xive_vm_esb_load(&state->ipi_data, XIVE_ESB_SET_PQ_10);
1053 	else
1054 		xive_vm_esb_load(&state->ipi_data, XIVE_ESB_SET_PQ_00);
1055 
1056 	/* Restore guest prio (unlocks EOI) */
1057 	mb();
1058 	state->guest_priority = prio;
1059 	arch_spin_unlock(&sb->lock);
1060 
1061 	return 0;
1062 }
1063 EXPORT_SYMBOL_GPL(kvmppc_xive_clr_mapped);
1064 
1065 void kvmppc_xive_disable_vcpu_interrupts(struct kvm_vcpu *vcpu)
1066 {
1067 	struct kvmppc_xive_vcpu *xc = vcpu->arch.xive_vcpu;
1068 	struct kvm *kvm = vcpu->kvm;
1069 	struct kvmppc_xive *xive = kvm->arch.xive;
1070 	int i, j;
1071 
1072 	for (i = 0; i <= xive->max_sbid; i++) {
1073 		struct kvmppc_xive_src_block *sb = xive->src_blocks[i];
1074 
1075 		if (!sb)
1076 			continue;
1077 		for (j = 0; j < KVMPPC_XICS_IRQ_PER_ICS; j++) {
1078 			struct kvmppc_xive_irq_state *state = &sb->irq_state[j];
1079 
1080 			if (!state->valid)
1081 				continue;
1082 			if (state->act_priority == MASKED)
1083 				continue;
1084 			if (state->act_server != xc->server_num)
1085 				continue;
1086 
1087 			/* Clean it up */
1088 			arch_spin_lock(&sb->lock);
1089 			state->act_priority = MASKED;
1090 			xive_vm_esb_load(&state->ipi_data, XIVE_ESB_SET_PQ_01);
1091 			xive_native_configure_irq(state->ipi_number, 0, MASKED, 0);
1092 			if (state->pt_number) {
1093 				xive_vm_esb_load(state->pt_data, XIVE_ESB_SET_PQ_01);
1094 				xive_native_configure_irq(state->pt_number, 0, MASKED, 0);
1095 			}
1096 			arch_spin_unlock(&sb->lock);
1097 		}
1098 	}
1099 
1100 	/* Disable vcpu's escalation interrupt */
1101 	if (vcpu->arch.xive_esc_on) {
1102 		__raw_readq((void __iomem *)(vcpu->arch.xive_esc_vaddr +
1103 					     XIVE_ESB_SET_PQ_01));
1104 		vcpu->arch.xive_esc_on = false;
1105 	}
1106 
1107 	/*
1108 	 * Clear pointers to escalation interrupt ESB.
1109 	 * This is safe because the vcpu->mutex is held, preventing
1110 	 * any other CPU from concurrently executing a KVM_RUN ioctl.
1111 	 */
1112 	vcpu->arch.xive_esc_vaddr = 0;
1113 	vcpu->arch.xive_esc_raddr = 0;
1114 }
1115 
1116 void kvmppc_xive_cleanup_vcpu(struct kvm_vcpu *vcpu)
1117 {
1118 	struct kvmppc_xive_vcpu *xc = vcpu->arch.xive_vcpu;
1119 	struct kvmppc_xive *xive = vcpu->kvm->arch.xive;
1120 	int i;
1121 
1122 	if (!kvmppc_xics_enabled(vcpu))
1123 		return;
1124 
1125 	if (!xc)
1126 		return;
1127 
1128 	pr_devel("cleanup_vcpu(cpu=%d)\n", xc->server_num);
1129 
1130 	/* Ensure no interrupt is still routed to that VP */
1131 	xc->valid = false;
1132 	kvmppc_xive_disable_vcpu_interrupts(vcpu);
1133 
1134 	/* Mask the VP IPI */
1135 	xive_vm_esb_load(&xc->vp_ipi_data, XIVE_ESB_SET_PQ_01);
1136 
1137 	/* Disable the VP */
1138 	xive_native_disable_vp(xc->vp_id);
1139 
1140 	/* Free the queues & associated interrupts */
1141 	for (i = 0; i < KVMPPC_XIVE_Q_COUNT; i++) {
1142 		struct xive_q *q = &xc->queues[i];
1143 
1144 		/* Free the escalation irq */
1145 		if (xc->esc_virq[i]) {
1146 			free_irq(xc->esc_virq[i], vcpu);
1147 			irq_dispose_mapping(xc->esc_virq[i]);
1148 			kfree(xc->esc_virq_names[i]);
1149 		}
1150 		/* Free the queue */
1151 		xive_native_disable_queue(xc->vp_id, q, i);
1152 		if (q->qpage) {
1153 			free_pages((unsigned long)q->qpage,
1154 				   xive->q_page_order);
1155 			q->qpage = NULL;
1156 		}
1157 	}
1158 
1159 	/* Free the IPI */
1160 	if (xc->vp_ipi) {
1161 		xive_cleanup_irq_data(&xc->vp_ipi_data);
1162 		xive_native_free_irq(xc->vp_ipi);
1163 	}
1164 	/* Free the VP */
1165 	kfree(xc);
1166 
1167 	/* Cleanup the vcpu */
1168 	vcpu->arch.irq_type = KVMPPC_IRQ_DEFAULT;
1169 	vcpu->arch.xive_vcpu = NULL;
1170 }
1171 
1172 int kvmppc_xive_connect_vcpu(struct kvm_device *dev,
1173 			     struct kvm_vcpu *vcpu, u32 cpu)
1174 {
1175 	struct kvmppc_xive *xive = dev->private;
1176 	struct kvmppc_xive_vcpu *xc;
1177 	int i, r = -EBUSY;
1178 
1179 	pr_devel("connect_vcpu(cpu=%d)\n", cpu);
1180 
1181 	if (dev->ops != &kvm_xive_ops) {
1182 		pr_devel("Wrong ops !\n");
1183 		return -EPERM;
1184 	}
1185 	if (xive->kvm != vcpu->kvm)
1186 		return -EPERM;
1187 	if (vcpu->arch.irq_type != KVMPPC_IRQ_DEFAULT)
1188 		return -EBUSY;
1189 	if (kvmppc_xive_find_server(vcpu->kvm, cpu)) {
1190 		pr_devel("Duplicate !\n");
1191 		return -EEXIST;
1192 	}
1193 	if (cpu >= (KVM_MAX_VCPUS * vcpu->kvm->arch.emul_smt_mode)) {
1194 		pr_devel("Out of bounds !\n");
1195 		return -EINVAL;
1196 	}
1197 	xc = kzalloc(sizeof(*xc), GFP_KERNEL);
1198 	if (!xc)
1199 		return -ENOMEM;
1200 
1201 	/* We need to synchronize with queue provisioning */
1202 	mutex_lock(&vcpu->kvm->lock);
1203 	vcpu->arch.xive_vcpu = xc;
1204 	xc->xive = xive;
1205 	xc->vcpu = vcpu;
1206 	xc->server_num = cpu;
1207 	xc->vp_id = kvmppc_xive_vp(xive, cpu);
1208 	xc->mfrr = 0xff;
1209 	xc->valid = true;
1210 
1211 	r = xive_native_get_vp_info(xc->vp_id, &xc->vp_cam, &xc->vp_chip_id);
1212 	if (r)
1213 		goto bail;
1214 
1215 	/* Configure VCPU fields for use by assembly push/pull */
1216 	vcpu->arch.xive_saved_state.w01 = cpu_to_be64(0xff000000);
1217 	vcpu->arch.xive_cam_word = cpu_to_be32(xc->vp_cam | TM_QW1W2_VO);
1218 
1219 	/* Allocate IPI */
1220 	xc->vp_ipi = xive_native_alloc_irq();
1221 	if (!xc->vp_ipi) {
1222 		pr_err("Failed to allocate xive irq for VCPU IPI\n");
1223 		r = -EIO;
1224 		goto bail;
1225 	}
1226 	pr_devel(" IPI=0x%x\n", xc->vp_ipi);
1227 
1228 	r = xive_native_populate_irq_data(xc->vp_ipi, &xc->vp_ipi_data);
1229 	if (r)
1230 		goto bail;
1231 
1232 	/*
1233 	 * Enable the VP first as the single escalation mode will
1234 	 * affect escalation interrupts numbering
1235 	 */
1236 	r = xive_native_enable_vp(xc->vp_id, xive->single_escalation);
1237 	if (r) {
1238 		pr_err("Failed to enable VP in OPAL, err %d\n", r);
1239 		goto bail;
1240 	}
1241 
1242 	/*
1243 	 * Initialize queues. Initially we set them all for no queueing
1244 	 * and we enable escalation for queue 0 only which we'll use for
1245 	 * our mfrr change notifications. If the VCPU is hot-plugged, we
1246 	 * do handle provisioning however based on the existing "map"
1247 	 * of enabled queues.
1248 	 */
1249 	for (i = 0; i < KVMPPC_XIVE_Q_COUNT; i++) {
1250 		struct xive_q *q = &xc->queues[i];
1251 
1252 		/* Single escalation, no queue 7 */
1253 		if (i == 7 && xive->single_escalation)
1254 			break;
1255 
1256 		/* Is queue already enabled ? Provision it */
1257 		if (xive->qmap & (1 << i)) {
1258 			r = xive_provision_queue(vcpu, i);
1259 			if (r == 0 && !xive->single_escalation)
1260 				kvmppc_xive_attach_escalation(
1261 					vcpu, i, xive->single_escalation);
1262 			if (r)
1263 				goto bail;
1264 		} else {
1265 			r = xive_native_configure_queue(xc->vp_id,
1266 							q, i, NULL, 0, true);
1267 			if (r) {
1268 				pr_err("Failed to configure queue %d for VCPU %d\n",
1269 				       i, cpu);
1270 				goto bail;
1271 			}
1272 		}
1273 	}
1274 
1275 	/* If not done above, attach priority 0 escalation */
1276 	r = kvmppc_xive_attach_escalation(vcpu, 0, xive->single_escalation);
1277 	if (r)
1278 		goto bail;
1279 
1280 	/* Route the IPI */
1281 	r = xive_native_configure_irq(xc->vp_ipi, xc->vp_id, 0, XICS_IPI);
1282 	if (!r)
1283 		xive_vm_esb_load(&xc->vp_ipi_data, XIVE_ESB_SET_PQ_00);
1284 
1285 bail:
1286 	mutex_unlock(&vcpu->kvm->lock);
1287 	if (r) {
1288 		kvmppc_xive_cleanup_vcpu(vcpu);
1289 		return r;
1290 	}
1291 
1292 	vcpu->arch.irq_type = KVMPPC_IRQ_XICS;
1293 	return 0;
1294 }
1295 
1296 /*
1297  * Scanning of queues before/after migration save
1298  */
1299 static void xive_pre_save_set_queued(struct kvmppc_xive *xive, u32 irq)
1300 {
1301 	struct kvmppc_xive_src_block *sb;
1302 	struct kvmppc_xive_irq_state *state;
1303 	u16 idx;
1304 
1305 	sb = kvmppc_xive_find_source(xive, irq, &idx);
1306 	if (!sb)
1307 		return;
1308 
1309 	state = &sb->irq_state[idx];
1310 
1311 	/* Some sanity checking */
1312 	if (!state->valid) {
1313 		pr_err("invalid irq 0x%x in cpu queue!\n", irq);
1314 		return;
1315 	}
1316 
1317 	/*
1318 	 * If the interrupt is in a queue it should have P set.
1319 	 * We warn so that gets reported. A backtrace isn't useful
1320 	 * so no need to use a WARN_ON.
1321 	 */
1322 	if (!state->saved_p)
1323 		pr_err("Interrupt 0x%x is marked in a queue but P not set !\n", irq);
1324 
1325 	/* Set flag */
1326 	state->in_queue = true;
1327 }
1328 
1329 static void xive_pre_save_mask_irq(struct kvmppc_xive *xive,
1330 				   struct kvmppc_xive_src_block *sb,
1331 				   u32 irq)
1332 {
1333 	struct kvmppc_xive_irq_state *state = &sb->irq_state[irq];
1334 
1335 	if (!state->valid)
1336 		return;
1337 
1338 	/* Mask and save state, this will also sync HW queues */
1339 	state->saved_scan_prio = xive_lock_and_mask(xive, sb, state);
1340 
1341 	/* Transfer P and Q */
1342 	state->saved_p = state->old_p;
1343 	state->saved_q = state->old_q;
1344 
1345 	/* Unlock */
1346 	arch_spin_unlock(&sb->lock);
1347 }
1348 
1349 static void xive_pre_save_unmask_irq(struct kvmppc_xive *xive,
1350 				     struct kvmppc_xive_src_block *sb,
1351 				     u32 irq)
1352 {
1353 	struct kvmppc_xive_irq_state *state = &sb->irq_state[irq];
1354 
1355 	if (!state->valid)
1356 		return;
1357 
1358 	/*
1359 	 * Lock / exclude EOI (not technically necessary if the
1360 	 * guest isn't running concurrently. If this becomes a
1361 	 * performance issue we can probably remove the lock.
1362 	 */
1363 	xive_lock_for_unmask(sb, state);
1364 
1365 	/* Restore mask/prio if it wasn't masked */
1366 	if (state->saved_scan_prio != MASKED)
1367 		xive_finish_unmask(xive, sb, state, state->saved_scan_prio);
1368 
1369 	/* Unlock */
1370 	arch_spin_unlock(&sb->lock);
1371 }
1372 
1373 static void xive_pre_save_queue(struct kvmppc_xive *xive, struct xive_q *q)
1374 {
1375 	u32 idx = q->idx;
1376 	u32 toggle = q->toggle;
1377 	u32 irq;
1378 
1379 	do {
1380 		irq = __xive_read_eq(q->qpage, q->msk, &idx, &toggle);
1381 		if (irq > XICS_IPI)
1382 			xive_pre_save_set_queued(xive, irq);
1383 	} while(irq);
1384 }
1385 
1386 static void xive_pre_save_scan(struct kvmppc_xive *xive)
1387 {
1388 	struct kvm_vcpu *vcpu = NULL;
1389 	int i, j;
1390 
1391 	/*
1392 	 * See comment in xive_get_source() about how this
1393 	 * work. Collect a stable state for all interrupts
1394 	 */
1395 	for (i = 0; i <= xive->max_sbid; i++) {
1396 		struct kvmppc_xive_src_block *sb = xive->src_blocks[i];
1397 		if (!sb)
1398 			continue;
1399 		for (j = 0;  j < KVMPPC_XICS_IRQ_PER_ICS; j++)
1400 			xive_pre_save_mask_irq(xive, sb, j);
1401 	}
1402 
1403 	/* Then scan the queues and update the "in_queue" flag */
1404 	kvm_for_each_vcpu(i, vcpu, xive->kvm) {
1405 		struct kvmppc_xive_vcpu *xc = vcpu->arch.xive_vcpu;
1406 		if (!xc)
1407 			continue;
1408 		for (j = 0; j < KVMPPC_XIVE_Q_COUNT; j++) {
1409 			if (xc->queues[j].qpage)
1410 				xive_pre_save_queue(xive, &xc->queues[j]);
1411 		}
1412 	}
1413 
1414 	/* Finally restore interrupt states */
1415 	for (i = 0; i <= xive->max_sbid; i++) {
1416 		struct kvmppc_xive_src_block *sb = xive->src_blocks[i];
1417 		if (!sb)
1418 			continue;
1419 		for (j = 0;  j < KVMPPC_XICS_IRQ_PER_ICS; j++)
1420 			xive_pre_save_unmask_irq(xive, sb, j);
1421 	}
1422 }
1423 
1424 static void xive_post_save_scan(struct kvmppc_xive *xive)
1425 {
1426 	u32 i, j;
1427 
1428 	/* Clear all the in_queue flags */
1429 	for (i = 0; i <= xive->max_sbid; i++) {
1430 		struct kvmppc_xive_src_block *sb = xive->src_blocks[i];
1431 		if (!sb)
1432 			continue;
1433 		for (j = 0;  j < KVMPPC_XICS_IRQ_PER_ICS; j++)
1434 			sb->irq_state[j].in_queue = false;
1435 	}
1436 
1437 	/* Next get_source() will do a new scan */
1438 	xive->saved_src_count = 0;
1439 }
1440 
1441 /*
1442  * This returns the source configuration and state to user space.
1443  */
1444 static int xive_get_source(struct kvmppc_xive *xive, long irq, u64 addr)
1445 {
1446 	struct kvmppc_xive_src_block *sb;
1447 	struct kvmppc_xive_irq_state *state;
1448 	u64 __user *ubufp = (u64 __user *) addr;
1449 	u64 val, prio;
1450 	u16 idx;
1451 
1452 	sb = kvmppc_xive_find_source(xive, irq, &idx);
1453 	if (!sb)
1454 		return -ENOENT;
1455 
1456 	state = &sb->irq_state[idx];
1457 
1458 	if (!state->valid)
1459 		return -ENOENT;
1460 
1461 	pr_devel("get_source(%ld)...\n", irq);
1462 
1463 	/*
1464 	 * So to properly save the state into something that looks like a
1465 	 * XICS migration stream we cannot treat interrupts individually.
1466 	 *
1467 	 * We need, instead, mask them all (& save their previous PQ state)
1468 	 * to get a stable state in the HW, then sync them to ensure that
1469 	 * any interrupt that had already fired hits its queue, and finally
1470 	 * scan all the queues to collect which interrupts are still present
1471 	 * in the queues, so we can set the "pending" flag on them and
1472 	 * they can be resent on restore.
1473 	 *
1474 	 * So we do it all when the "first" interrupt gets saved, all the
1475 	 * state is collected at that point, the rest of xive_get_source()
1476 	 * will merely collect and convert that state to the expected
1477 	 * userspace bit mask.
1478 	 */
1479 	if (xive->saved_src_count == 0)
1480 		xive_pre_save_scan(xive);
1481 	xive->saved_src_count++;
1482 
1483 	/* Convert saved state into something compatible with xics */
1484 	val = state->act_server;
1485 	prio = state->saved_scan_prio;
1486 
1487 	if (prio == MASKED) {
1488 		val |= KVM_XICS_MASKED;
1489 		prio = state->saved_priority;
1490 	}
1491 	val |= prio << KVM_XICS_PRIORITY_SHIFT;
1492 	if (state->lsi) {
1493 		val |= KVM_XICS_LEVEL_SENSITIVE;
1494 		if (state->saved_p)
1495 			val |= KVM_XICS_PENDING;
1496 	} else {
1497 		if (state->saved_p)
1498 			val |= KVM_XICS_PRESENTED;
1499 
1500 		if (state->saved_q)
1501 			val |= KVM_XICS_QUEUED;
1502 
1503 		/*
1504 		 * We mark it pending (which will attempt a re-delivery)
1505 		 * if we are in a queue *or* we were masked and had
1506 		 * Q set which is equivalent to the XICS "masked pending"
1507 		 * state
1508 		 */
1509 		if (state->in_queue || (prio == MASKED && state->saved_q))
1510 			val |= KVM_XICS_PENDING;
1511 	}
1512 
1513 	/*
1514 	 * If that was the last interrupt saved, reset the
1515 	 * in_queue flags
1516 	 */
1517 	if (xive->saved_src_count == xive->src_count)
1518 		xive_post_save_scan(xive);
1519 
1520 	/* Copy the result to userspace */
1521 	if (put_user(val, ubufp))
1522 		return -EFAULT;
1523 
1524 	return 0;
1525 }
1526 
1527 struct kvmppc_xive_src_block *kvmppc_xive_create_src_block(
1528 	struct kvmppc_xive *xive, int irq)
1529 {
1530 	struct kvm *kvm = xive->kvm;
1531 	struct kvmppc_xive_src_block *sb;
1532 	int i, bid;
1533 
1534 	bid = irq >> KVMPPC_XICS_ICS_SHIFT;
1535 
1536 	mutex_lock(&kvm->lock);
1537 
1538 	/* block already exists - somebody else got here first */
1539 	if (xive->src_blocks[bid])
1540 		goto out;
1541 
1542 	/* Create the ICS */
1543 	sb = kzalloc(sizeof(*sb), GFP_KERNEL);
1544 	if (!sb)
1545 		goto out;
1546 
1547 	sb->id = bid;
1548 
1549 	for (i = 0; i < KVMPPC_XICS_IRQ_PER_ICS; i++) {
1550 		sb->irq_state[i].number = (bid << KVMPPC_XICS_ICS_SHIFT) | i;
1551 		sb->irq_state[i].eisn = 0;
1552 		sb->irq_state[i].guest_priority = MASKED;
1553 		sb->irq_state[i].saved_priority = MASKED;
1554 		sb->irq_state[i].act_priority = MASKED;
1555 	}
1556 	smp_wmb();
1557 	xive->src_blocks[bid] = sb;
1558 
1559 	if (bid > xive->max_sbid)
1560 		xive->max_sbid = bid;
1561 
1562 out:
1563 	mutex_unlock(&kvm->lock);
1564 	return xive->src_blocks[bid];
1565 }
1566 
1567 static bool xive_check_delayed_irq(struct kvmppc_xive *xive, u32 irq)
1568 {
1569 	struct kvm *kvm = xive->kvm;
1570 	struct kvm_vcpu *vcpu = NULL;
1571 	int i;
1572 
1573 	kvm_for_each_vcpu(i, vcpu, kvm) {
1574 		struct kvmppc_xive_vcpu *xc = vcpu->arch.xive_vcpu;
1575 
1576 		if (!xc)
1577 			continue;
1578 
1579 		if (xc->delayed_irq == irq) {
1580 			xc->delayed_irq = 0;
1581 			xive->delayed_irqs--;
1582 			return true;
1583 		}
1584 	}
1585 	return false;
1586 }
1587 
1588 static int xive_set_source(struct kvmppc_xive *xive, long irq, u64 addr)
1589 {
1590 	struct kvmppc_xive_src_block *sb;
1591 	struct kvmppc_xive_irq_state *state;
1592 	u64 __user *ubufp = (u64 __user *) addr;
1593 	u16 idx;
1594 	u64 val;
1595 	u8 act_prio, guest_prio;
1596 	u32 server;
1597 	int rc = 0;
1598 
1599 	if (irq < KVMPPC_XICS_FIRST_IRQ || irq >= KVMPPC_XICS_NR_IRQS)
1600 		return -ENOENT;
1601 
1602 	pr_devel("set_source(irq=0x%lx)\n", irq);
1603 
1604 	/* Find the source */
1605 	sb = kvmppc_xive_find_source(xive, irq, &idx);
1606 	if (!sb) {
1607 		pr_devel("No source, creating source block...\n");
1608 		sb = kvmppc_xive_create_src_block(xive, irq);
1609 		if (!sb) {
1610 			pr_devel("Failed to create block...\n");
1611 			return -ENOMEM;
1612 		}
1613 	}
1614 	state = &sb->irq_state[idx];
1615 
1616 	/* Read user passed data */
1617 	if (get_user(val, ubufp)) {
1618 		pr_devel("fault getting user info !\n");
1619 		return -EFAULT;
1620 	}
1621 
1622 	server = val & KVM_XICS_DESTINATION_MASK;
1623 	guest_prio = val >> KVM_XICS_PRIORITY_SHIFT;
1624 
1625 	pr_devel("  val=0x016%llx (server=0x%x, guest_prio=%d)\n",
1626 		 val, server, guest_prio);
1627 
1628 	/*
1629 	 * If the source doesn't already have an IPI, allocate
1630 	 * one and get the corresponding data
1631 	 */
1632 	if (!state->ipi_number) {
1633 		state->ipi_number = xive_native_alloc_irq();
1634 		if (state->ipi_number == 0) {
1635 			pr_devel("Failed to allocate IPI !\n");
1636 			return -ENOMEM;
1637 		}
1638 		xive_native_populate_irq_data(state->ipi_number, &state->ipi_data);
1639 		pr_devel(" src_ipi=0x%x\n", state->ipi_number);
1640 	}
1641 
1642 	/*
1643 	 * We use lock_and_mask() to set us in the right masked
1644 	 * state. We will override that state from the saved state
1645 	 * further down, but this will handle the cases of interrupts
1646 	 * that need FW masking. We set the initial guest_priority to
1647 	 * 0 before calling it to ensure it actually performs the masking.
1648 	 */
1649 	state->guest_priority = 0;
1650 	xive_lock_and_mask(xive, sb, state);
1651 
1652 	/*
1653 	 * Now, we select a target if we have one. If we don't we
1654 	 * leave the interrupt untargetted. It means that an interrupt
1655 	 * can become "untargetted" accross migration if it was masked
1656 	 * by set_xive() but there is little we can do about it.
1657 	 */
1658 
1659 	/* First convert prio and mark interrupt as untargetted */
1660 	act_prio = xive_prio_from_guest(guest_prio);
1661 	state->act_priority = MASKED;
1662 
1663 	/*
1664 	 * We need to drop the lock due to the mutex below. Hopefully
1665 	 * nothing is touching that interrupt yet since it hasn't been
1666 	 * advertized to a running guest yet
1667 	 */
1668 	arch_spin_unlock(&sb->lock);
1669 
1670 	/* If we have a priority target the interrupt */
1671 	if (act_prio != MASKED) {
1672 		/* First, check provisioning of queues */
1673 		mutex_lock(&xive->kvm->lock);
1674 		rc = xive_check_provisioning(xive->kvm, act_prio);
1675 		mutex_unlock(&xive->kvm->lock);
1676 
1677 		/* Target interrupt */
1678 		if (rc == 0)
1679 			rc = xive_target_interrupt(xive->kvm, state,
1680 						   server, act_prio);
1681 		/*
1682 		 * If provisioning or targetting failed, leave it
1683 		 * alone and masked. It will remain disabled until
1684 		 * the guest re-targets it.
1685 		 */
1686 	}
1687 
1688 	/*
1689 	 * Find out if this was a delayed irq stashed in an ICP,
1690 	 * in which case, treat it as pending
1691 	 */
1692 	if (xive->delayed_irqs && xive_check_delayed_irq(xive, irq)) {
1693 		val |= KVM_XICS_PENDING;
1694 		pr_devel("  Found delayed ! forcing PENDING !\n");
1695 	}
1696 
1697 	/* Cleanup the SW state */
1698 	state->old_p = false;
1699 	state->old_q = false;
1700 	state->lsi = false;
1701 	state->asserted = false;
1702 
1703 	/* Restore LSI state */
1704 	if (val & KVM_XICS_LEVEL_SENSITIVE) {
1705 		state->lsi = true;
1706 		if (val & KVM_XICS_PENDING)
1707 			state->asserted = true;
1708 		pr_devel("  LSI ! Asserted=%d\n", state->asserted);
1709 	}
1710 
1711 	/*
1712 	 * Restore P and Q. If the interrupt was pending, we
1713 	 * force Q and !P, which will trigger a resend.
1714 	 *
1715 	 * That means that a guest that had both an interrupt
1716 	 * pending (queued) and Q set will restore with only
1717 	 * one instance of that interrupt instead of 2, but that
1718 	 * is perfectly fine as coalescing interrupts that haven't
1719 	 * been presented yet is always allowed.
1720 	 */
1721 	if (val & KVM_XICS_PRESENTED && !(val & KVM_XICS_PENDING))
1722 		state->old_p = true;
1723 	if (val & KVM_XICS_QUEUED || val & KVM_XICS_PENDING)
1724 		state->old_q = true;
1725 
1726 	pr_devel("  P=%d, Q=%d\n", state->old_p, state->old_q);
1727 
1728 	/*
1729 	 * If the interrupt was unmasked, update guest priority and
1730 	 * perform the appropriate state transition and do a
1731 	 * re-trigger if necessary.
1732 	 */
1733 	if (val & KVM_XICS_MASKED) {
1734 		pr_devel("  masked, saving prio\n");
1735 		state->guest_priority = MASKED;
1736 		state->saved_priority = guest_prio;
1737 	} else {
1738 		pr_devel("  unmasked, restoring to prio %d\n", guest_prio);
1739 		xive_finish_unmask(xive, sb, state, guest_prio);
1740 		state->saved_priority = guest_prio;
1741 	}
1742 
1743 	/* Increment the number of valid sources and mark this one valid */
1744 	if (!state->valid)
1745 		xive->src_count++;
1746 	state->valid = true;
1747 
1748 	return 0;
1749 }
1750 
1751 int kvmppc_xive_set_irq(struct kvm *kvm, int irq_source_id, u32 irq, int level,
1752 			bool line_status)
1753 {
1754 	struct kvmppc_xive *xive = kvm->arch.xive;
1755 	struct kvmppc_xive_src_block *sb;
1756 	struct kvmppc_xive_irq_state *state;
1757 	u16 idx;
1758 
1759 	if (!xive)
1760 		return -ENODEV;
1761 
1762 	sb = kvmppc_xive_find_source(xive, irq, &idx);
1763 	if (!sb)
1764 		return -EINVAL;
1765 
1766 	/* Perform locklessly .... (we need to do some RCUisms here...) */
1767 	state = &sb->irq_state[idx];
1768 	if (!state->valid)
1769 		return -EINVAL;
1770 
1771 	/* We don't allow a trigger on a passed-through interrupt */
1772 	if (state->pt_number)
1773 		return -EINVAL;
1774 
1775 	if ((level == 1 && state->lsi) || level == KVM_INTERRUPT_SET_LEVEL)
1776 		state->asserted = 1;
1777 	else if (level == 0 || level == KVM_INTERRUPT_UNSET) {
1778 		state->asserted = 0;
1779 		return 0;
1780 	}
1781 
1782 	/* Trigger the IPI */
1783 	xive_irq_trigger(&state->ipi_data);
1784 
1785 	return 0;
1786 }
1787 
1788 static int xive_set_attr(struct kvm_device *dev, struct kvm_device_attr *attr)
1789 {
1790 	struct kvmppc_xive *xive = dev->private;
1791 
1792 	/* We honor the existing XICS ioctl */
1793 	switch (attr->group) {
1794 	case KVM_DEV_XICS_GRP_SOURCES:
1795 		return xive_set_source(xive, attr->attr, attr->addr);
1796 	}
1797 	return -ENXIO;
1798 }
1799 
1800 static int xive_get_attr(struct kvm_device *dev, struct kvm_device_attr *attr)
1801 {
1802 	struct kvmppc_xive *xive = dev->private;
1803 
1804 	/* We honor the existing XICS ioctl */
1805 	switch (attr->group) {
1806 	case KVM_DEV_XICS_GRP_SOURCES:
1807 		return xive_get_source(xive, attr->attr, attr->addr);
1808 	}
1809 	return -ENXIO;
1810 }
1811 
1812 static int xive_has_attr(struct kvm_device *dev, struct kvm_device_attr *attr)
1813 {
1814 	/* We honor the same limits as XICS, at least for now */
1815 	switch (attr->group) {
1816 	case KVM_DEV_XICS_GRP_SOURCES:
1817 		if (attr->attr >= KVMPPC_XICS_FIRST_IRQ &&
1818 		    attr->attr < KVMPPC_XICS_NR_IRQS)
1819 			return 0;
1820 		break;
1821 	}
1822 	return -ENXIO;
1823 }
1824 
1825 static void kvmppc_xive_cleanup_irq(u32 hw_num, struct xive_irq_data *xd)
1826 {
1827 	xive_vm_esb_load(xd, XIVE_ESB_SET_PQ_01);
1828 	xive_native_configure_irq(hw_num, 0, MASKED, 0);
1829 	xive_cleanup_irq_data(xd);
1830 }
1831 
1832 void kvmppc_xive_free_sources(struct kvmppc_xive_src_block *sb)
1833 {
1834 	int i;
1835 
1836 	for (i = 0; i < KVMPPC_XICS_IRQ_PER_ICS; i++) {
1837 		struct kvmppc_xive_irq_state *state = &sb->irq_state[i];
1838 
1839 		if (!state->valid)
1840 			continue;
1841 
1842 		kvmppc_xive_cleanup_irq(state->ipi_number, &state->ipi_data);
1843 		xive_native_free_irq(state->ipi_number);
1844 
1845 		/* Pass-through, cleanup too */
1846 		if (state->pt_number)
1847 			kvmppc_xive_cleanup_irq(state->pt_number, state->pt_data);
1848 
1849 		state->valid = false;
1850 	}
1851 }
1852 
1853 /*
1854  * Called when device fd is closed.  kvm->lock is held.
1855  */
1856 static void kvmppc_xive_release(struct kvm_device *dev)
1857 {
1858 	struct kvmppc_xive *xive = dev->private;
1859 	struct kvm *kvm = xive->kvm;
1860 	struct kvm_vcpu *vcpu;
1861 	int i;
1862 	int was_ready;
1863 
1864 	pr_devel("Releasing xive device\n");
1865 
1866 	debugfs_remove(xive->dentry);
1867 
1868 	/*
1869 	 * Clearing mmu_ready temporarily while holding kvm->lock
1870 	 * is a way of ensuring that no vcpus can enter the guest
1871 	 * until we drop kvm->lock.  Doing kick_all_cpus_sync()
1872 	 * ensures that any vcpu executing inside the guest has
1873 	 * exited the guest.  Once kick_all_cpus_sync() has finished,
1874 	 * we know that no vcpu can be executing the XIVE push or
1875 	 * pull code, or executing a XICS hcall.
1876 	 *
1877 	 * Since this is the device release function, we know that
1878 	 * userspace does not have any open fd referring to the
1879 	 * device.  Therefore there can not be any of the device
1880 	 * attribute set/get functions being executed concurrently,
1881 	 * and similarly, the connect_vcpu and set/clr_mapped
1882 	 * functions also cannot be being executed.
1883 	 */
1884 	was_ready = kvm->arch.mmu_ready;
1885 	kvm->arch.mmu_ready = 0;
1886 	kick_all_cpus_sync();
1887 
1888 	/*
1889 	 * We should clean up the vCPU interrupt presenters first.
1890 	 */
1891 	kvm_for_each_vcpu(i, vcpu, kvm) {
1892 		/*
1893 		 * Take vcpu->mutex to ensure that no one_reg get/set ioctl
1894 		 * (i.e. kvmppc_xive_[gs]et_icp) can be done concurrently.
1895 		 */
1896 		mutex_lock(&vcpu->mutex);
1897 		kvmppc_xive_cleanup_vcpu(vcpu);
1898 		mutex_unlock(&vcpu->mutex);
1899 	}
1900 
1901 	kvm->arch.xive = NULL;
1902 
1903 	/* Mask and free interrupts */
1904 	for (i = 0; i <= xive->max_sbid; i++) {
1905 		if (xive->src_blocks[i])
1906 			kvmppc_xive_free_sources(xive->src_blocks[i]);
1907 		kfree(xive->src_blocks[i]);
1908 		xive->src_blocks[i] = NULL;
1909 	}
1910 
1911 	if (xive->vp_base != XIVE_INVALID_VP)
1912 		xive_native_free_vp_block(xive->vp_base);
1913 
1914 	kvm->arch.mmu_ready = was_ready;
1915 
1916 	/*
1917 	 * A reference of the kvmppc_xive pointer is now kept under
1918 	 * the xive_devices struct of the machine for reuse. It is
1919 	 * freed when the VM is destroyed for now until we fix all the
1920 	 * execution paths.
1921 	 */
1922 
1923 	kfree(dev);
1924 }
1925 
1926 /*
1927  * When the guest chooses the interrupt mode (XICS legacy or XIVE
1928  * native), the VM will switch of KVM device. The previous device will
1929  * be "released" before the new one is created.
1930  *
1931  * Until we are sure all execution paths are well protected, provide a
1932  * fail safe (transitional) method for device destruction, in which
1933  * the XIVE device pointer is recycled and not directly freed.
1934  */
1935 struct kvmppc_xive *kvmppc_xive_get_device(struct kvm *kvm, u32 type)
1936 {
1937 	struct kvmppc_xive **kvm_xive_device = type == KVM_DEV_TYPE_XIVE ?
1938 		&kvm->arch.xive_devices.native :
1939 		&kvm->arch.xive_devices.xics_on_xive;
1940 	struct kvmppc_xive *xive = *kvm_xive_device;
1941 
1942 	if (!xive) {
1943 		xive = kzalloc(sizeof(*xive), GFP_KERNEL);
1944 		*kvm_xive_device = xive;
1945 	} else {
1946 		memset(xive, 0, sizeof(*xive));
1947 	}
1948 
1949 	return xive;
1950 }
1951 
1952 /*
1953  * Create a XICS device with XIVE backend.  kvm->lock is held.
1954  */
1955 static int kvmppc_xive_create(struct kvm_device *dev, u32 type)
1956 {
1957 	struct kvmppc_xive *xive;
1958 	struct kvm *kvm = dev->kvm;
1959 	int ret = 0;
1960 
1961 	pr_devel("Creating xive for partition\n");
1962 
1963 	xive = kvmppc_xive_get_device(kvm, type);
1964 	if (!xive)
1965 		return -ENOMEM;
1966 
1967 	dev->private = xive;
1968 	xive->dev = dev;
1969 	xive->kvm = kvm;
1970 
1971 	/* Already there ? */
1972 	if (kvm->arch.xive)
1973 		ret = -EEXIST;
1974 	else
1975 		kvm->arch.xive = xive;
1976 
1977 	/* We use the default queue size set by the host */
1978 	xive->q_order = xive_native_default_eq_shift();
1979 	if (xive->q_order < PAGE_SHIFT)
1980 		xive->q_page_order = 0;
1981 	else
1982 		xive->q_page_order = xive->q_order - PAGE_SHIFT;
1983 
1984 	/* Allocate a bunch of VPs */
1985 	xive->vp_base = xive_native_alloc_vp_block(KVM_MAX_VCPUS);
1986 	pr_devel("VP_Base=%x\n", xive->vp_base);
1987 
1988 	if (xive->vp_base == XIVE_INVALID_VP)
1989 		ret = -ENOMEM;
1990 
1991 	xive->single_escalation = xive_native_has_single_escalation();
1992 
1993 	if (ret) {
1994 		kfree(xive);
1995 		return ret;
1996 	}
1997 
1998 	return 0;
1999 }
2000 
2001 int kvmppc_xive_debug_show_queues(struct seq_file *m, struct kvm_vcpu *vcpu)
2002 {
2003 	struct kvmppc_xive_vcpu *xc = vcpu->arch.xive_vcpu;
2004 	unsigned int i;
2005 
2006 	for (i = 0; i < KVMPPC_XIVE_Q_COUNT; i++) {
2007 		struct xive_q *q = &xc->queues[i];
2008 		u32 i0, i1, idx;
2009 
2010 		if (!q->qpage && !xc->esc_virq[i])
2011 			continue;
2012 
2013 		seq_printf(m, " [q%d]: ", i);
2014 
2015 		if (q->qpage) {
2016 			idx = q->idx;
2017 			i0 = be32_to_cpup(q->qpage + idx);
2018 			idx = (idx + 1) & q->msk;
2019 			i1 = be32_to_cpup(q->qpage + idx);
2020 			seq_printf(m, "T=%d %08x %08x...\n", q->toggle,
2021 				   i0, i1);
2022 		}
2023 		if (xc->esc_virq[i]) {
2024 			struct irq_data *d = irq_get_irq_data(xc->esc_virq[i]);
2025 			struct xive_irq_data *xd =
2026 				irq_data_get_irq_handler_data(d);
2027 			u64 pq = xive_vm_esb_load(xd, XIVE_ESB_GET);
2028 
2029 			seq_printf(m, "E:%c%c I(%d:%llx:%llx)",
2030 				   (pq & XIVE_ESB_VAL_P) ? 'P' : 'p',
2031 				   (pq & XIVE_ESB_VAL_Q) ? 'Q' : 'q',
2032 				   xc->esc_virq[i], pq, xd->eoi_page);
2033 			seq_puts(m, "\n");
2034 		}
2035 	}
2036 	return 0;
2037 }
2038 
2039 static int xive_debug_show(struct seq_file *m, void *private)
2040 {
2041 	struct kvmppc_xive *xive = m->private;
2042 	struct kvm *kvm = xive->kvm;
2043 	struct kvm_vcpu *vcpu;
2044 	u64 t_rm_h_xirr = 0;
2045 	u64 t_rm_h_ipoll = 0;
2046 	u64 t_rm_h_cppr = 0;
2047 	u64 t_rm_h_eoi = 0;
2048 	u64 t_rm_h_ipi = 0;
2049 	u64 t_vm_h_xirr = 0;
2050 	u64 t_vm_h_ipoll = 0;
2051 	u64 t_vm_h_cppr = 0;
2052 	u64 t_vm_h_eoi = 0;
2053 	u64 t_vm_h_ipi = 0;
2054 	unsigned int i;
2055 
2056 	if (!kvm)
2057 		return 0;
2058 
2059 	seq_printf(m, "=========\nVCPU state\n=========\n");
2060 
2061 	kvm_for_each_vcpu(i, vcpu, kvm) {
2062 		struct kvmppc_xive_vcpu *xc = vcpu->arch.xive_vcpu;
2063 
2064 		if (!xc)
2065 			continue;
2066 
2067 		seq_printf(m, "cpu server %#x CPPR:%#x HWCPPR:%#x"
2068 			   " MFRR:%#x PEND:%#x h_xirr: R=%lld V=%lld\n",
2069 			   xc->server_num, xc->cppr, xc->hw_cppr,
2070 			   xc->mfrr, xc->pending,
2071 			   xc->stat_rm_h_xirr, xc->stat_vm_h_xirr);
2072 
2073 		kvmppc_xive_debug_show_queues(m, vcpu);
2074 
2075 		t_rm_h_xirr += xc->stat_rm_h_xirr;
2076 		t_rm_h_ipoll += xc->stat_rm_h_ipoll;
2077 		t_rm_h_cppr += xc->stat_rm_h_cppr;
2078 		t_rm_h_eoi += xc->stat_rm_h_eoi;
2079 		t_rm_h_ipi += xc->stat_rm_h_ipi;
2080 		t_vm_h_xirr += xc->stat_vm_h_xirr;
2081 		t_vm_h_ipoll += xc->stat_vm_h_ipoll;
2082 		t_vm_h_cppr += xc->stat_vm_h_cppr;
2083 		t_vm_h_eoi += xc->stat_vm_h_eoi;
2084 		t_vm_h_ipi += xc->stat_vm_h_ipi;
2085 	}
2086 
2087 	seq_printf(m, "Hcalls totals\n");
2088 	seq_printf(m, " H_XIRR  R=%10lld V=%10lld\n", t_rm_h_xirr, t_vm_h_xirr);
2089 	seq_printf(m, " H_IPOLL R=%10lld V=%10lld\n", t_rm_h_ipoll, t_vm_h_ipoll);
2090 	seq_printf(m, " H_CPPR  R=%10lld V=%10lld\n", t_rm_h_cppr, t_vm_h_cppr);
2091 	seq_printf(m, " H_EOI   R=%10lld V=%10lld\n", t_rm_h_eoi, t_vm_h_eoi);
2092 	seq_printf(m, " H_IPI   R=%10lld V=%10lld\n", t_rm_h_ipi, t_vm_h_ipi);
2093 
2094 	return 0;
2095 }
2096 
2097 DEFINE_SHOW_ATTRIBUTE(xive_debug);
2098 
2099 static void xive_debugfs_init(struct kvmppc_xive *xive)
2100 {
2101 	char *name;
2102 
2103 	name = kasprintf(GFP_KERNEL, "kvm-xive-%p", xive);
2104 	if (!name) {
2105 		pr_err("%s: no memory for name\n", __func__);
2106 		return;
2107 	}
2108 
2109 	xive->dentry = debugfs_create_file(name, S_IRUGO, powerpc_debugfs_root,
2110 					   xive, &xive_debug_fops);
2111 
2112 	pr_debug("%s: created %s\n", __func__, name);
2113 	kfree(name);
2114 }
2115 
2116 static void kvmppc_xive_init(struct kvm_device *dev)
2117 {
2118 	struct kvmppc_xive *xive = (struct kvmppc_xive *)dev->private;
2119 
2120 	/* Register some debug interfaces */
2121 	xive_debugfs_init(xive);
2122 }
2123 
2124 struct kvm_device_ops kvm_xive_ops = {
2125 	.name = "kvm-xive",
2126 	.create = kvmppc_xive_create,
2127 	.init = kvmppc_xive_init,
2128 	.release = kvmppc_xive_release,
2129 	.set_attr = xive_set_attr,
2130 	.get_attr = xive_get_attr,
2131 	.has_attr = xive_has_attr,
2132 };
2133 
2134 void kvmppc_xive_init_module(void)
2135 {
2136 	__xive_vm_h_xirr = xive_vm_h_xirr;
2137 	__xive_vm_h_ipoll = xive_vm_h_ipoll;
2138 	__xive_vm_h_ipi = xive_vm_h_ipi;
2139 	__xive_vm_h_cppr = xive_vm_h_cppr;
2140 	__xive_vm_h_eoi = xive_vm_h_eoi;
2141 }
2142 
2143 void kvmppc_xive_exit_module(void)
2144 {
2145 	__xive_vm_h_xirr = NULL;
2146 	__xive_vm_h_ipoll = NULL;
2147 	__xive_vm_h_ipi = NULL;
2148 	__xive_vm_h_cppr = NULL;
2149 	__xive_vm_h_eoi = NULL;
2150 }
2151