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