xref: /openbmc/qemu/hw/intc/spapr_xive_kvm.c (revision 3885ca66881f1d2568e169dcbf793fd493146d14)
1 /*
2  * QEMU PowerPC sPAPR XIVE interrupt controller model
3  *
4  * Copyright (c) 2017-2019, IBM Corporation.
5  *
6  * This code is licensed under the GPL version 2 or later. See the
7  * COPYING file in the top-level directory.
8  */
9 
10 #include "qemu/osdep.h"
11 #include "qemu/log.h"
12 #include "qemu/error-report.h"
13 #include "qapi/error.h"
14 #include "target/ppc/cpu.h"
15 #include "sysemu/cpus.h"
16 #include "sysemu/kvm.h"
17 #include "sysemu/runstate.h"
18 #include "hw/ppc/spapr.h"
19 #include "hw/ppc/spapr_cpu_core.h"
20 #include "hw/ppc/spapr_xive.h"
21 #include "hw/ppc/xive.h"
22 #include "kvm_ppc.h"
23 
24 #include <sys/ioctl.h>
25 
26 /*
27  * Helpers for CPU hotplug
28  *
29  * TODO: make a common KVMEnabledCPU layer for XICS and XIVE
30  */
31 typedef struct KVMEnabledCPU {
32     unsigned long vcpu_id;
33     QLIST_ENTRY(KVMEnabledCPU) node;
34 } KVMEnabledCPU;
35 
36 static QLIST_HEAD(, KVMEnabledCPU)
37     kvm_enabled_cpus = QLIST_HEAD_INITIALIZER(&kvm_enabled_cpus);
38 
39 static bool kvm_cpu_is_enabled(CPUState *cs)
40 {
41     KVMEnabledCPU *enabled_cpu;
42     unsigned long vcpu_id = kvm_arch_vcpu_id(cs);
43 
44     QLIST_FOREACH(enabled_cpu, &kvm_enabled_cpus, node) {
45         if (enabled_cpu->vcpu_id == vcpu_id) {
46             return true;
47         }
48     }
49     return false;
50 }
51 
52 static void kvm_cpu_enable(CPUState *cs)
53 {
54     KVMEnabledCPU *enabled_cpu;
55     unsigned long vcpu_id = kvm_arch_vcpu_id(cs);
56 
57     enabled_cpu = g_malloc(sizeof(*enabled_cpu));
58     enabled_cpu->vcpu_id = vcpu_id;
59     QLIST_INSERT_HEAD(&kvm_enabled_cpus, enabled_cpu, node);
60 }
61 
62 static void kvm_cpu_disable_all(void)
63 {
64     KVMEnabledCPU *enabled_cpu, *next;
65 
66     QLIST_FOREACH_SAFE(enabled_cpu, &kvm_enabled_cpus, node, next) {
67         QLIST_REMOVE(enabled_cpu, node);
68         g_free(enabled_cpu);
69     }
70 }
71 
72 /*
73  * XIVE Thread Interrupt Management context (KVM)
74  */
75 
76 void kvmppc_xive_cpu_set_state(XiveTCTX *tctx, Error **errp)
77 {
78     SpaprXive *xive = SPAPR_XIVE(tctx->xptr);
79     uint64_t state[2];
80     int ret;
81 
82     assert(xive->fd != -1);
83 
84     /* word0 and word1 of the OS ring. */
85     state[0] = *((uint64_t *) &tctx->regs[TM_QW1_OS]);
86 
87     ret = kvm_set_one_reg(tctx->cs, KVM_REG_PPC_VP_STATE, state);
88     if (ret != 0) {
89         error_setg_errno(errp, errno,
90                          "XIVE: could not restore KVM state of CPU %ld",
91                          kvm_arch_vcpu_id(tctx->cs));
92     }
93 }
94 
95 void kvmppc_xive_cpu_get_state(XiveTCTX *tctx, Error **errp)
96 {
97     SpaprXive *xive = SPAPR_XIVE(tctx->xptr);
98     uint64_t state[2] = { 0 };
99     int ret;
100 
101     assert(xive->fd != -1);
102 
103     ret = kvm_get_one_reg(tctx->cs, KVM_REG_PPC_VP_STATE, state);
104     if (ret != 0) {
105         error_setg_errno(errp, errno,
106                          "XIVE: could not capture KVM state of CPU %ld",
107                          kvm_arch_vcpu_id(tctx->cs));
108         return;
109     }
110 
111     /* word0 and word1 of the OS ring. */
112     *((uint64_t *) &tctx->regs[TM_QW1_OS]) = state[0];
113 }
114 
115 typedef struct {
116     XiveTCTX *tctx;
117     Error *err;
118 } XiveCpuGetState;
119 
120 static void kvmppc_xive_cpu_do_synchronize_state(CPUState *cpu,
121                                                  run_on_cpu_data arg)
122 {
123     XiveCpuGetState *s = arg.host_ptr;
124 
125     kvmppc_xive_cpu_get_state(s->tctx, &s->err);
126 }
127 
128 void kvmppc_xive_cpu_synchronize_state(XiveTCTX *tctx, Error **errp)
129 {
130     XiveCpuGetState s = {
131         .tctx = tctx,
132         .err = NULL,
133     };
134 
135     /*
136      * Kick the vCPU to make sure they are available for the KVM ioctl.
137      */
138     run_on_cpu(tctx->cs, kvmppc_xive_cpu_do_synchronize_state,
139                RUN_ON_CPU_HOST_PTR(&s));
140 
141     if (s.err) {
142         error_propagate(errp, s.err);
143         return;
144     }
145 }
146 
147 int kvmppc_xive_cpu_connect(XiveTCTX *tctx, Error **errp)
148 {
149     ERRP_GUARD();
150     SpaprXive *xive = SPAPR_XIVE(tctx->xptr);
151     unsigned long vcpu_id;
152     int ret;
153 
154     assert(xive->fd != -1);
155 
156     /* Check if CPU was hot unplugged and replugged. */
157     if (kvm_cpu_is_enabled(tctx->cs)) {
158         return 0;
159     }
160 
161     vcpu_id = kvm_arch_vcpu_id(tctx->cs);
162 
163     ret = kvm_vcpu_enable_cap(tctx->cs, KVM_CAP_PPC_IRQ_XIVE, 0, xive->fd,
164                               vcpu_id, 0);
165     if (ret < 0) {
166         error_setg_errno(errp, -ret,
167                          "XIVE: unable to connect CPU%ld to KVM device",
168                          vcpu_id);
169         if (ret == -ENOSPC) {
170             error_append_hint(errp, "Try -smp maxcpus=N with N < %u\n",
171                               MACHINE(qdev_get_machine())->smp.max_cpus);
172         }
173         return ret;
174     }
175 
176     kvm_cpu_enable(tctx->cs);
177     return 0;
178 }
179 
180 /*
181  * XIVE Interrupt Source (KVM)
182  */
183 
184 void kvmppc_xive_set_source_config(SpaprXive *xive, uint32_t lisn, XiveEAS *eas,
185                                    Error **errp)
186 {
187     uint32_t end_idx;
188     uint32_t end_blk;
189     uint8_t priority;
190     uint32_t server;
191     bool masked;
192     uint32_t eisn;
193     uint64_t kvm_src;
194     Error *local_err = NULL;
195 
196     assert(xive_eas_is_valid(eas));
197 
198     end_idx = xive_get_field64(EAS_END_INDEX, eas->w);
199     end_blk = xive_get_field64(EAS_END_BLOCK, eas->w);
200     eisn = xive_get_field64(EAS_END_DATA, eas->w);
201     masked = xive_eas_is_masked(eas);
202 
203     spapr_xive_end_to_target(end_blk, end_idx, &server, &priority);
204 
205     kvm_src = priority << KVM_XIVE_SOURCE_PRIORITY_SHIFT &
206         KVM_XIVE_SOURCE_PRIORITY_MASK;
207     kvm_src |= server << KVM_XIVE_SOURCE_SERVER_SHIFT &
208         KVM_XIVE_SOURCE_SERVER_MASK;
209     kvm_src |= ((uint64_t) masked << KVM_XIVE_SOURCE_MASKED_SHIFT) &
210         KVM_XIVE_SOURCE_MASKED_MASK;
211     kvm_src |= ((uint64_t)eisn << KVM_XIVE_SOURCE_EISN_SHIFT) &
212         KVM_XIVE_SOURCE_EISN_MASK;
213 
214     kvm_device_access(xive->fd, KVM_DEV_XIVE_GRP_SOURCE_CONFIG, lisn,
215                       &kvm_src, true, &local_err);
216     if (local_err) {
217         error_propagate(errp, local_err);
218         return;
219     }
220 }
221 
222 void kvmppc_xive_sync_source(SpaprXive *xive, uint32_t lisn, Error **errp)
223 {
224     kvm_device_access(xive->fd, KVM_DEV_XIVE_GRP_SOURCE_SYNC, lisn,
225                       NULL, true, errp);
226 }
227 
228 /*
229  * At reset, the interrupt sources are simply created and MASKED. We
230  * only need to inform the KVM XIVE device about their type: LSI or
231  * MSI.
232  */
233 int kvmppc_xive_source_reset_one(XiveSource *xsrc, int srcno, Error **errp)
234 {
235     SpaprXive *xive = SPAPR_XIVE(xsrc->xive);
236     uint64_t state = 0;
237 
238     assert(xive->fd != -1);
239 
240     if (xive_source_irq_is_lsi(xsrc, srcno)) {
241         state |= KVM_XIVE_LEVEL_SENSITIVE;
242         if (xsrc->status[srcno] & XIVE_STATUS_ASSERTED) {
243             state |= KVM_XIVE_LEVEL_ASSERTED;
244         }
245     }
246 
247     return kvm_device_access(xive->fd, KVM_DEV_XIVE_GRP_SOURCE, srcno, &state,
248                              true, errp);
249 }
250 
251 static void kvmppc_xive_source_reset(XiveSource *xsrc, Error **errp)
252 {
253     SpaprXive *xive = SPAPR_XIVE(xsrc->xive);
254     int i;
255 
256     for (i = 0; i < xsrc->nr_irqs; i++) {
257         Error *local_err = NULL;
258 
259         if (!xive_eas_is_valid(&xive->eat[i])) {
260             continue;
261         }
262 
263         kvmppc_xive_source_reset_one(xsrc, i, &local_err);
264         if (local_err) {
265             error_propagate(errp, local_err);
266             return;
267         }
268     }
269 }
270 
271 /*
272  * This is used to perform the magic loads on the ESB pages, described
273  * in xive.h.
274  *
275  * Memory barriers should not be needed for loads (no store for now).
276  */
277 static uint64_t xive_esb_rw(XiveSource *xsrc, int srcno, uint32_t offset,
278                             uint64_t data, bool write)
279 {
280     uint64_t *addr = xsrc->esb_mmap + xive_source_esb_mgmt(xsrc, srcno) +
281         offset;
282 
283     if (write) {
284         *addr = cpu_to_be64(data);
285         return -1;
286     } else {
287         /* Prevent the compiler from optimizing away the load */
288         volatile uint64_t value = be64_to_cpu(*addr);
289         return value;
290     }
291 }
292 
293 static uint8_t xive_esb_read(XiveSource *xsrc, int srcno, uint32_t offset)
294 {
295     return xive_esb_rw(xsrc, srcno, offset, 0, 0) & 0x3;
296 }
297 
298 static void xive_esb_trigger(XiveSource *xsrc, int srcno)
299 {
300     uint64_t *addr = xsrc->esb_mmap + xive_source_esb_page(xsrc, srcno);
301 
302     *addr = 0x0;
303 }
304 
305 uint64_t kvmppc_xive_esb_rw(XiveSource *xsrc, int srcno, uint32_t offset,
306                             uint64_t data, bool write)
307 {
308     if (write) {
309         return xive_esb_rw(xsrc, srcno, offset, data, 1);
310     }
311 
312     /*
313      * Special Load EOI handling for LSI sources. Q bit is never set
314      * and the interrupt should be re-triggered if the level is still
315      * asserted.
316      */
317     if (xive_source_irq_is_lsi(xsrc, srcno) &&
318         offset == XIVE_ESB_LOAD_EOI) {
319         xive_esb_read(xsrc, srcno, XIVE_ESB_SET_PQ_00);
320         if (xsrc->status[srcno] & XIVE_STATUS_ASSERTED) {
321             xive_esb_trigger(xsrc, srcno);
322         }
323         return 0;
324     } else {
325         return xive_esb_rw(xsrc, srcno, offset, 0, 0);
326     }
327 }
328 
329 static void kvmppc_xive_source_get_state(XiveSource *xsrc)
330 {
331     SpaprXive *xive = SPAPR_XIVE(xsrc->xive);
332     int i;
333 
334     for (i = 0; i < xsrc->nr_irqs; i++) {
335         uint8_t pq;
336 
337         if (!xive_eas_is_valid(&xive->eat[i])) {
338             continue;
339         }
340 
341         /* Perform a load without side effect to retrieve the PQ bits */
342         pq = xive_esb_read(xsrc, i, XIVE_ESB_GET);
343 
344         /* and save PQ locally */
345         xive_source_esb_set(xsrc, i, pq);
346     }
347 }
348 
349 void kvmppc_xive_source_set_irq(void *opaque, int srcno, int val)
350 {
351     XiveSource *xsrc = opaque;
352 
353     if (!xive_source_irq_is_lsi(xsrc, srcno)) {
354         if (!val) {
355             return;
356         }
357     } else {
358         if (val) {
359             xsrc->status[srcno] |= XIVE_STATUS_ASSERTED;
360         } else {
361             xsrc->status[srcno] &= ~XIVE_STATUS_ASSERTED;
362         }
363     }
364 
365     xive_esb_trigger(xsrc, srcno);
366 }
367 
368 /*
369  * sPAPR XIVE interrupt controller (KVM)
370  */
371 void kvmppc_xive_get_queue_config(SpaprXive *xive, uint8_t end_blk,
372                                   uint32_t end_idx, XiveEND *end,
373                                   Error **errp)
374 {
375     struct kvm_ppc_xive_eq kvm_eq = { 0 };
376     uint64_t kvm_eq_idx;
377     uint8_t priority;
378     uint32_t server;
379     Error *local_err = NULL;
380 
381     assert(xive_end_is_valid(end));
382 
383     /* Encode the tuple (server, prio) as a KVM EQ index */
384     spapr_xive_end_to_target(end_blk, end_idx, &server, &priority);
385 
386     kvm_eq_idx = priority << KVM_XIVE_EQ_PRIORITY_SHIFT &
387             KVM_XIVE_EQ_PRIORITY_MASK;
388     kvm_eq_idx |= server << KVM_XIVE_EQ_SERVER_SHIFT &
389         KVM_XIVE_EQ_SERVER_MASK;
390 
391     kvm_device_access(xive->fd, KVM_DEV_XIVE_GRP_EQ_CONFIG, kvm_eq_idx,
392                       &kvm_eq, false, &local_err);
393     if (local_err) {
394         error_propagate(errp, local_err);
395         return;
396     }
397 
398     /*
399      * The EQ index and toggle bit are updated by HW. These are the
400      * only fields from KVM we want to update QEMU with. The other END
401      * fields should already be in the QEMU END table.
402      */
403     end->w1 = xive_set_field32(END_W1_GENERATION, 0ul, kvm_eq.qtoggle) |
404         xive_set_field32(END_W1_PAGE_OFF, 0ul, kvm_eq.qindex);
405 }
406 
407 void kvmppc_xive_set_queue_config(SpaprXive *xive, uint8_t end_blk,
408                                   uint32_t end_idx, XiveEND *end,
409                                   Error **errp)
410 {
411     struct kvm_ppc_xive_eq kvm_eq = { 0 };
412     uint64_t kvm_eq_idx;
413     uint8_t priority;
414     uint32_t server;
415     Error *local_err = NULL;
416 
417     /*
418      * Build the KVM state from the local END structure.
419      */
420 
421     kvm_eq.flags = 0;
422     if (xive_get_field32(END_W0_UCOND_NOTIFY, end->w0)) {
423         kvm_eq.flags |= KVM_XIVE_EQ_ALWAYS_NOTIFY;
424     }
425 
426     /*
427      * If the hcall is disabling the EQ, set the size and page address
428      * to zero. When migrating, only valid ENDs are taken into
429      * account.
430      */
431     if (xive_end_is_valid(end)) {
432         kvm_eq.qshift = xive_get_field32(END_W0_QSIZE, end->w0) + 12;
433         kvm_eq.qaddr  = xive_end_qaddr(end);
434         /*
435          * The EQ toggle bit and index should only be relevant when
436          * restoring the EQ state
437          */
438         kvm_eq.qtoggle = xive_get_field32(END_W1_GENERATION, end->w1);
439         kvm_eq.qindex  = xive_get_field32(END_W1_PAGE_OFF, end->w1);
440     } else {
441         kvm_eq.qshift = 0;
442         kvm_eq.qaddr  = 0;
443     }
444 
445     /* Encode the tuple (server, prio) as a KVM EQ index */
446     spapr_xive_end_to_target(end_blk, end_idx, &server, &priority);
447 
448     kvm_eq_idx = priority << KVM_XIVE_EQ_PRIORITY_SHIFT &
449             KVM_XIVE_EQ_PRIORITY_MASK;
450     kvm_eq_idx |= server << KVM_XIVE_EQ_SERVER_SHIFT &
451         KVM_XIVE_EQ_SERVER_MASK;
452 
453     kvm_device_access(xive->fd, KVM_DEV_XIVE_GRP_EQ_CONFIG, kvm_eq_idx,
454                       &kvm_eq, true, &local_err);
455     if (local_err) {
456         error_propagate(errp, local_err);
457         return;
458     }
459 }
460 
461 void kvmppc_xive_reset(SpaprXive *xive, Error **errp)
462 {
463     kvm_device_access(xive->fd, KVM_DEV_XIVE_GRP_CTRL, KVM_DEV_XIVE_RESET,
464                       NULL, true, errp);
465 }
466 
467 static void kvmppc_xive_get_queues(SpaprXive *xive, Error **errp)
468 {
469     Error *local_err = NULL;
470     int i;
471 
472     for (i = 0; i < xive->nr_ends; i++) {
473         if (!xive_end_is_valid(&xive->endt[i])) {
474             continue;
475         }
476 
477         kvmppc_xive_get_queue_config(xive, SPAPR_XIVE_BLOCK_ID, i,
478                                      &xive->endt[i], &local_err);
479         if (local_err) {
480             error_propagate(errp, local_err);
481             return;
482         }
483     }
484 }
485 
486 /*
487  * The primary goal of the XIVE VM change handler is to mark the EQ
488  * pages dirty when all XIVE event notifications have stopped.
489  *
490  * Whenever the VM is stopped, the VM change handler sets the source
491  * PQs to PENDING to stop the flow of events and to possibly catch a
492  * triggered interrupt occuring while the VM is stopped. The previous
493  * state is saved in anticipation of a migration. The XIVE controller
494  * is then synced through KVM to flush any in-flight event
495  * notification and stabilize the EQs.
496  *
497  * At this stage, we can mark the EQ page dirty and let a migration
498  * sequence transfer the EQ pages to the destination, which is done
499  * just after the stop state.
500  *
501  * The previous configuration of the sources is restored when the VM
502  * runs again. If an interrupt was queued while the VM was stopped,
503  * simply generate a trigger.
504  */
505 static void kvmppc_xive_change_state_handler(void *opaque, int running,
506                                              RunState state)
507 {
508     SpaprXive *xive = opaque;
509     XiveSource *xsrc = &xive->source;
510     Error *local_err = NULL;
511     int i;
512 
513     /*
514      * Restore the sources to their initial state. This is called when
515      * the VM resumes after a stop or a migration.
516      */
517     if (running) {
518         for (i = 0; i < xsrc->nr_irqs; i++) {
519             uint8_t pq;
520             uint8_t old_pq;
521 
522             if (!xive_eas_is_valid(&xive->eat[i])) {
523                 continue;
524             }
525 
526             pq = xive_source_esb_get(xsrc, i);
527             old_pq = xive_esb_read(xsrc, i, XIVE_ESB_SET_PQ_00 + (pq << 8));
528 
529             /*
530              * An interrupt was queued while the VM was stopped,
531              * generate a trigger.
532              */
533             if (pq == XIVE_ESB_RESET && old_pq == XIVE_ESB_QUEUED) {
534                 xive_esb_trigger(xsrc, i);
535             }
536         }
537 
538         return;
539     }
540 
541     /*
542      * Mask the sources, to stop the flow of event notifications, and
543      * save the PQs locally in the XiveSource object. The XiveSource
544      * state will be collected later on by its vmstate handler if a
545      * migration is in progress.
546      */
547     for (i = 0; i < xsrc->nr_irqs; i++) {
548         uint8_t pq;
549 
550         if (!xive_eas_is_valid(&xive->eat[i])) {
551             continue;
552         }
553 
554         pq = xive_esb_read(xsrc, i, XIVE_ESB_GET);
555 
556         /*
557          * PQ is set to PENDING to possibly catch a triggered
558          * interrupt occuring while the VM is stopped (hotplug event
559          * for instance) .
560          */
561         if (pq != XIVE_ESB_OFF) {
562             pq = xive_esb_read(xsrc, i, XIVE_ESB_SET_PQ_10);
563         }
564         xive_source_esb_set(xsrc, i, pq);
565     }
566 
567     /*
568      * Sync the XIVE controller in KVM, to flush in-flight event
569      * notification that should be enqueued in the EQs and mark the
570      * XIVE EQ pages dirty to collect all updates.
571      */
572     kvm_device_access(xive->fd, KVM_DEV_XIVE_GRP_CTRL,
573                       KVM_DEV_XIVE_EQ_SYNC, NULL, true, &local_err);
574     if (local_err) {
575         error_report_err(local_err);
576         return;
577     }
578 }
579 
580 void kvmppc_xive_synchronize_state(SpaprXive *xive, Error **errp)
581 {
582     assert(xive->fd != -1);
583 
584     /*
585      * When the VM is stopped, the sources are masked and the previous
586      * state is saved in anticipation of a migration. We should not
587      * synchronize the source state in that case else we will override
588      * the saved state.
589      */
590     if (runstate_is_running()) {
591         kvmppc_xive_source_get_state(&xive->source);
592     }
593 
594     /* EAT: there is no extra state to query from KVM */
595 
596     /* ENDT */
597     kvmppc_xive_get_queues(xive, errp);
598 }
599 
600 /*
601  * The SpaprXive 'pre_save' method is called by the vmstate handler of
602  * the SpaprXive model, after the XIVE controller is synced in the VM
603  * change handler.
604  */
605 int kvmppc_xive_pre_save(SpaprXive *xive)
606 {
607     Error *local_err = NULL;
608 
609     assert(xive->fd != -1);
610 
611     /* EAT: there is no extra state to query from KVM */
612 
613     /* ENDT */
614     kvmppc_xive_get_queues(xive, &local_err);
615     if (local_err) {
616         error_report_err(local_err);
617         return -1;
618     }
619 
620     return 0;
621 }
622 
623 /*
624  * The SpaprXive 'post_load' method is not called by a vmstate
625  * handler. It is called at the sPAPR machine level at the end of the
626  * migration sequence by the sPAPR IRQ backend 'post_load' method,
627  * when all XIVE states have been transferred and loaded.
628  */
629 int kvmppc_xive_post_load(SpaprXive *xive, int version_id)
630 {
631     Error *local_err = NULL;
632     CPUState *cs;
633     int i;
634 
635     /* The KVM XIVE device should be in use */
636     assert(xive->fd != -1);
637 
638     /* Restore the ENDT first. The targetting depends on it. */
639     for (i = 0; i < xive->nr_ends; i++) {
640         if (!xive_end_is_valid(&xive->endt[i])) {
641             continue;
642         }
643 
644         kvmppc_xive_set_queue_config(xive, SPAPR_XIVE_BLOCK_ID, i,
645                                      &xive->endt[i], &local_err);
646         if (local_err) {
647             error_report_err(local_err);
648             return -1;
649         }
650     }
651 
652     /* Restore the EAT */
653     for (i = 0; i < xive->nr_irqs; i++) {
654         if (!xive_eas_is_valid(&xive->eat[i])) {
655             continue;
656         }
657 
658         /*
659          * We can only restore the source config if the source has been
660          * previously set in KVM. Since we don't do that for all interrupts
661          * at reset time anymore, let's do it now.
662          */
663         kvmppc_xive_source_reset_one(&xive->source, i, &local_err);
664         if (local_err) {
665             error_report_err(local_err);
666             return -1;
667         }
668 
669         kvmppc_xive_set_source_config(xive, i, &xive->eat[i], &local_err);
670         if (local_err) {
671             error_report_err(local_err);
672             return -1;
673         }
674     }
675 
676     /*
677      * Restore the thread interrupt contexts of initial CPUs.
678      *
679      * The context of hotplugged CPUs is restored later, by the
680      * 'post_load' handler of the XiveTCTX model because they are not
681      * available at the time the SpaprXive 'post_load' method is
682      * called. We can not restore the context of all CPUs in the
683      * 'post_load' handler of XiveTCTX because the machine is not
684      * necessarily connected to the KVM device at that time.
685      */
686     CPU_FOREACH(cs) {
687         PowerPCCPU *cpu = POWERPC_CPU(cs);
688 
689         kvmppc_xive_cpu_set_state(spapr_cpu_state(cpu)->tctx, &local_err);
690         if (local_err) {
691             error_report_err(local_err);
692             return -1;
693         }
694     }
695 
696     /* The source states will be restored when the machine starts running */
697     return 0;
698 }
699 
700 static void *kvmppc_xive_mmap(SpaprXive *xive, int pgoff, size_t len,
701                               Error **errp)
702 {
703     void *addr;
704     uint32_t page_shift = 16; /* TODO: fix page_shift */
705 
706     addr = mmap(NULL, len, PROT_WRITE | PROT_READ, MAP_SHARED, xive->fd,
707                 pgoff << page_shift);
708     if (addr == MAP_FAILED) {
709         error_setg_errno(errp, errno, "XIVE: unable to set memory mapping");
710         return NULL;
711     }
712 
713     return addr;
714 }
715 
716 /*
717  * All the XIVE memory regions are now backed by mappings from the KVM
718  * XIVE device.
719  */
720 int kvmppc_xive_connect(SpaprInterruptController *intc, uint32_t nr_servers,
721                         Error **errp)
722 {
723     SpaprXive *xive = SPAPR_XIVE(intc);
724     XiveSource *xsrc = &xive->source;
725     Error *local_err = NULL;
726     size_t esb_len = xive_source_esb_len(xsrc);
727     size_t tima_len = 4ull << TM_SHIFT;
728     CPUState *cs;
729     int fd;
730 
731     /*
732      * The KVM XIVE device already in use. This is the case when
733      * rebooting under the XIVE-only interrupt mode.
734      */
735     if (xive->fd != -1) {
736         return 0;
737     }
738 
739     if (!kvmppc_has_cap_xive()) {
740         error_setg(errp, "IRQ_XIVE capability must be present for KVM");
741         return -1;
742     }
743 
744     /* First, create the KVM XIVE device */
745     fd = kvm_create_device(kvm_state, KVM_DEV_TYPE_XIVE, false);
746     if (fd < 0) {
747         error_setg_errno(errp, -fd, "XIVE: error creating KVM device");
748         return -1;
749     }
750     xive->fd = fd;
751 
752     /* Tell KVM about the # of VCPUs we may have */
753     if (kvm_device_check_attr(xive->fd, KVM_DEV_XIVE_GRP_CTRL,
754                               KVM_DEV_XIVE_NR_SERVERS)) {
755         if (kvm_device_access(xive->fd, KVM_DEV_XIVE_GRP_CTRL,
756                               KVM_DEV_XIVE_NR_SERVERS, &nr_servers, true,
757                               &local_err)) {
758             goto fail;
759         }
760     }
761 
762     /*
763      * 1. Source ESB pages - KVM mapping
764      */
765     xsrc->esb_mmap = kvmppc_xive_mmap(xive, KVM_XIVE_ESB_PAGE_OFFSET, esb_len,
766                                       &local_err);
767     if (local_err) {
768         goto fail;
769     }
770 
771     memory_region_init_ram_device_ptr(&xsrc->esb_mmio_kvm, OBJECT(xsrc),
772                                       "xive.esb-kvm", esb_len, xsrc->esb_mmap);
773     memory_region_add_subregion_overlap(&xsrc->esb_mmio, 0,
774                                         &xsrc->esb_mmio_kvm, 1);
775 
776     /*
777      * 2. END ESB pages (No KVM support yet)
778      */
779 
780     /*
781      * 3. TIMA pages - KVM mapping
782      */
783     xive->tm_mmap = kvmppc_xive_mmap(xive, KVM_XIVE_TIMA_PAGE_OFFSET, tima_len,
784                                      &local_err);
785     if (local_err) {
786         goto fail;
787     }
788     memory_region_init_ram_device_ptr(&xive->tm_mmio_kvm, OBJECT(xive),
789                                       "xive.tima", tima_len, xive->tm_mmap);
790     memory_region_add_subregion_overlap(&xive->tm_mmio, 0,
791                                         &xive->tm_mmio_kvm, 1);
792 
793     xive->change = qemu_add_vm_change_state_handler(
794         kvmppc_xive_change_state_handler, xive);
795 
796     /* Connect the presenters to the initial VCPUs of the machine */
797     CPU_FOREACH(cs) {
798         PowerPCCPU *cpu = POWERPC_CPU(cs);
799 
800         kvmppc_xive_cpu_connect(spapr_cpu_state(cpu)->tctx, &local_err);
801         if (local_err) {
802             goto fail;
803         }
804     }
805 
806     /* Update the KVM sources */
807     kvmppc_xive_source_reset(xsrc, &local_err);
808     if (local_err) {
809         goto fail;
810     }
811 
812     kvm_kernel_irqchip = true;
813     kvm_msi_via_irqfd_allowed = true;
814     kvm_gsi_direct_mapping = true;
815     return 0;
816 
817 fail:
818     error_propagate(errp, local_err);
819     kvmppc_xive_disconnect(intc);
820     return -1;
821 }
822 
823 void kvmppc_xive_disconnect(SpaprInterruptController *intc)
824 {
825     SpaprXive *xive = SPAPR_XIVE(intc);
826     XiveSource *xsrc;
827     size_t esb_len;
828 
829     assert(xive->fd != -1);
830 
831     /* Clear the KVM mapping */
832     xsrc = &xive->source;
833     esb_len = (1ull << xsrc->esb_shift) * xsrc->nr_irqs;
834 
835     if (xsrc->esb_mmap) {
836         memory_region_del_subregion(&xsrc->esb_mmio, &xsrc->esb_mmio_kvm);
837         object_unparent(OBJECT(&xsrc->esb_mmio_kvm));
838         munmap(xsrc->esb_mmap, esb_len);
839         xsrc->esb_mmap = NULL;
840     }
841 
842     if (xive->tm_mmap) {
843         memory_region_del_subregion(&xive->tm_mmio, &xive->tm_mmio_kvm);
844         object_unparent(OBJECT(&xive->tm_mmio_kvm));
845         munmap(xive->tm_mmap, 4ull << TM_SHIFT);
846         xive->tm_mmap = NULL;
847     }
848 
849     /*
850      * When the KVM device fd is closed, the KVM device is destroyed
851      * and removed from the list of devices of the VM. The VCPU
852      * presenters are also detached from the device.
853      */
854     close(xive->fd);
855     xive->fd = -1;
856 
857     kvm_kernel_irqchip = false;
858     kvm_msi_via_irqfd_allowed = false;
859     kvm_gsi_direct_mapping = false;
860 
861     /* Clear the local list of presenter (hotplug) */
862     kvm_cpu_disable_all();
863 
864     /* VM Change state handler is not needed anymore */
865     if (xive->change) {
866         qemu_del_vm_change_state_handler(xive->change);
867         xive->change = NULL;
868     }
869 }
870