xref: /openbmc/qemu/hw/intc/spapr_xive_kvm.c (revision 42a92d925d03ec49dfdefb43c15b46c3ca55f9e4)
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 int 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, -ret,
90                          "XIVE: could not restore KVM state of CPU %ld",
91                          kvm_arch_vcpu_id(tctx->cs));
92         return ret;
93     }
94 
95     return 0;
96 }
97 
98 int kvmppc_xive_cpu_get_state(XiveTCTX *tctx, Error **errp)
99 {
100     SpaprXive *xive = SPAPR_XIVE(tctx->xptr);
101     uint64_t state[2] = { 0 };
102     int ret;
103 
104     assert(xive->fd != -1);
105 
106     ret = kvm_get_one_reg(tctx->cs, KVM_REG_PPC_VP_STATE, state);
107     if (ret != 0) {
108         error_setg_errno(errp, -ret,
109                          "XIVE: could not capture KVM state of CPU %ld",
110                          kvm_arch_vcpu_id(tctx->cs));
111         return ret;
112     }
113 
114     /* word0 and word1 of the OS ring. */
115     *((uint64_t *) &tctx->regs[TM_QW1_OS]) = state[0];
116 
117     return 0;
118 }
119 
120 typedef struct {
121     XiveTCTX *tctx;
122     Error *err;
123 } XiveCpuGetState;
124 
125 static void kvmppc_xive_cpu_do_synchronize_state(CPUState *cpu,
126                                                  run_on_cpu_data arg)
127 {
128     XiveCpuGetState *s = arg.host_ptr;
129 
130     kvmppc_xive_cpu_get_state(s->tctx, &s->err);
131 }
132 
133 void kvmppc_xive_cpu_synchronize_state(XiveTCTX *tctx, Error **errp)
134 {
135     XiveCpuGetState s = {
136         .tctx = tctx,
137         .err = NULL,
138     };
139 
140     /*
141      * Kick the vCPU to make sure they are available for the KVM ioctl.
142      */
143     run_on_cpu(tctx->cs, kvmppc_xive_cpu_do_synchronize_state,
144                RUN_ON_CPU_HOST_PTR(&s));
145 
146     if (s.err) {
147         error_propagate(errp, s.err);
148         return;
149     }
150 }
151 
152 int kvmppc_xive_cpu_connect(XiveTCTX *tctx, Error **errp)
153 {
154     ERRP_GUARD();
155     SpaprXive *xive = SPAPR_XIVE(tctx->xptr);
156     unsigned long vcpu_id;
157     int ret;
158 
159     assert(xive->fd != -1);
160 
161     /* Check if CPU was hot unplugged and replugged. */
162     if (kvm_cpu_is_enabled(tctx->cs)) {
163         return 0;
164     }
165 
166     vcpu_id = kvm_arch_vcpu_id(tctx->cs);
167 
168     ret = kvm_vcpu_enable_cap(tctx->cs, KVM_CAP_PPC_IRQ_XIVE, 0, xive->fd,
169                               vcpu_id, 0);
170     if (ret < 0) {
171         error_setg_errno(errp, -ret,
172                          "XIVE: unable to connect CPU%ld to KVM device",
173                          vcpu_id);
174         if (ret == -ENOSPC) {
175             error_append_hint(errp, "Try -smp maxcpus=N with N < %u\n",
176                               MACHINE(qdev_get_machine())->smp.max_cpus);
177         }
178         return ret;
179     }
180 
181     kvm_cpu_enable(tctx->cs);
182     return 0;
183 }
184 
185 /*
186  * XIVE Interrupt Source (KVM)
187  */
188 
189 int kvmppc_xive_set_source_config(SpaprXive *xive, uint32_t lisn, XiveEAS *eas,
190                                   Error **errp)
191 {
192     uint32_t end_idx;
193     uint32_t end_blk;
194     uint8_t priority;
195     uint32_t server;
196     bool masked;
197     uint32_t eisn;
198     uint64_t kvm_src;
199 
200     assert(xive_eas_is_valid(eas));
201 
202     end_idx = xive_get_field64(EAS_END_INDEX, eas->w);
203     end_blk = xive_get_field64(EAS_END_BLOCK, eas->w);
204     eisn = xive_get_field64(EAS_END_DATA, eas->w);
205     masked = xive_eas_is_masked(eas);
206 
207     spapr_xive_end_to_target(end_blk, end_idx, &server, &priority);
208 
209     kvm_src = priority << KVM_XIVE_SOURCE_PRIORITY_SHIFT &
210         KVM_XIVE_SOURCE_PRIORITY_MASK;
211     kvm_src |= server << KVM_XIVE_SOURCE_SERVER_SHIFT &
212         KVM_XIVE_SOURCE_SERVER_MASK;
213     kvm_src |= ((uint64_t) masked << KVM_XIVE_SOURCE_MASKED_SHIFT) &
214         KVM_XIVE_SOURCE_MASKED_MASK;
215     kvm_src |= ((uint64_t)eisn << KVM_XIVE_SOURCE_EISN_SHIFT) &
216         KVM_XIVE_SOURCE_EISN_MASK;
217 
218     return kvm_device_access(xive->fd, KVM_DEV_XIVE_GRP_SOURCE_CONFIG, lisn,
219                              &kvm_src, true, errp);
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 int 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         int ret;
258 
259         if (!xive_eas_is_valid(&xive->eat[i])) {
260             continue;
261         }
262 
263         ret = kvmppc_xive_source_reset_one(xsrc, i, errp);
264         if (ret < 0) {
265             return ret;
266         }
267     }
268 
269     return 0;
270 }
271 
272 /*
273  * This is used to perform the magic loads on the ESB pages, described
274  * in xive.h.
275  *
276  * Memory barriers should not be needed for loads (no store for now).
277  */
278 static uint64_t xive_esb_rw(XiveSource *xsrc, int srcno, uint32_t offset,
279                             uint64_t data, bool write)
280 {
281     uint64_t *addr = xsrc->esb_mmap + xive_source_esb_mgmt(xsrc, srcno) +
282         offset;
283 
284     if (write) {
285         *addr = cpu_to_be64(data);
286         return -1;
287     } else {
288         /* Prevent the compiler from optimizing away the load */
289         volatile uint64_t value = be64_to_cpu(*addr);
290         return value;
291     }
292 }
293 
294 static uint8_t xive_esb_read(XiveSource *xsrc, int srcno, uint32_t offset)
295 {
296     return xive_esb_rw(xsrc, srcno, offset, 0, 0) & 0x3;
297 }
298 
299 static void xive_esb_trigger(XiveSource *xsrc, int srcno)
300 {
301     uint64_t *addr = xsrc->esb_mmap + xive_source_esb_page(xsrc, srcno);
302 
303     *addr = 0x0;
304 }
305 
306 uint64_t kvmppc_xive_esb_rw(XiveSource *xsrc, int srcno, uint32_t offset,
307                             uint64_t data, bool write)
308 {
309     if (write) {
310         return xive_esb_rw(xsrc, srcno, offset, data, 1);
311     }
312 
313     /*
314      * Special Load EOI handling for LSI sources. Q bit is never set
315      * and the interrupt should be re-triggered if the level is still
316      * asserted.
317      */
318     if (xive_source_irq_is_lsi(xsrc, srcno) &&
319         offset == XIVE_ESB_LOAD_EOI) {
320         xive_esb_read(xsrc, srcno, XIVE_ESB_SET_PQ_00);
321         if (xsrc->status[srcno] & XIVE_STATUS_ASSERTED) {
322             xive_esb_trigger(xsrc, srcno);
323         }
324         return 0;
325     } else {
326         return xive_esb_rw(xsrc, srcno, offset, 0, 0);
327     }
328 }
329 
330 static void kvmppc_xive_source_get_state(XiveSource *xsrc)
331 {
332     SpaprXive *xive = SPAPR_XIVE(xsrc->xive);
333     int i;
334 
335     for (i = 0; i < xsrc->nr_irqs; i++) {
336         uint8_t pq;
337 
338         if (!xive_eas_is_valid(&xive->eat[i])) {
339             continue;
340         }
341 
342         /* Perform a load without side effect to retrieve the PQ bits */
343         pq = xive_esb_read(xsrc, i, XIVE_ESB_GET);
344 
345         /* and save PQ locally */
346         xive_source_esb_set(xsrc, i, pq);
347     }
348 }
349 
350 void kvmppc_xive_source_set_irq(void *opaque, int srcno, int val)
351 {
352     XiveSource *xsrc = opaque;
353 
354     if (!xive_source_irq_is_lsi(xsrc, srcno)) {
355         if (!val) {
356             return;
357         }
358     } else {
359         if (val) {
360             xsrc->status[srcno] |= XIVE_STATUS_ASSERTED;
361         } else {
362             xsrc->status[srcno] &= ~XIVE_STATUS_ASSERTED;
363         }
364     }
365 
366     xive_esb_trigger(xsrc, srcno);
367 }
368 
369 /*
370  * sPAPR XIVE interrupt controller (KVM)
371  */
372 int kvmppc_xive_get_queue_config(SpaprXive *xive, uint8_t end_blk,
373                                  uint32_t end_idx, XiveEND *end,
374                                  Error **errp)
375 {
376     struct kvm_ppc_xive_eq kvm_eq = { 0 };
377     uint64_t kvm_eq_idx;
378     uint8_t priority;
379     uint32_t server;
380     int ret;
381 
382     assert(xive_end_is_valid(end));
383 
384     /* Encode the tuple (server, prio) as a KVM EQ index */
385     spapr_xive_end_to_target(end_blk, end_idx, &server, &priority);
386 
387     kvm_eq_idx = priority << KVM_XIVE_EQ_PRIORITY_SHIFT &
388             KVM_XIVE_EQ_PRIORITY_MASK;
389     kvm_eq_idx |= server << KVM_XIVE_EQ_SERVER_SHIFT &
390         KVM_XIVE_EQ_SERVER_MASK;
391 
392     ret = kvm_device_access(xive->fd, KVM_DEV_XIVE_GRP_EQ_CONFIG, kvm_eq_idx,
393                             &kvm_eq, false, errp);
394     if (ret < 0) {
395         return ret;
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     return 0;
407 }
408 
409 int kvmppc_xive_set_queue_config(SpaprXive *xive, uint8_t end_blk,
410                                  uint32_t end_idx, XiveEND *end,
411                                  Error **errp)
412 {
413     struct kvm_ppc_xive_eq kvm_eq = { 0 };
414     uint64_t kvm_eq_idx;
415     uint8_t priority;
416     uint32_t server;
417 
418     /*
419      * Build the KVM state from the local END structure.
420      */
421 
422     kvm_eq.flags = 0;
423     if (xive_get_field32(END_W0_UCOND_NOTIFY, end->w0)) {
424         kvm_eq.flags |= KVM_XIVE_EQ_ALWAYS_NOTIFY;
425     }
426 
427     /*
428      * If the hcall is disabling the EQ, set the size and page address
429      * to zero. When migrating, only valid ENDs are taken into
430      * account.
431      */
432     if (xive_end_is_valid(end)) {
433         kvm_eq.qshift = xive_get_field32(END_W0_QSIZE, end->w0) + 12;
434         kvm_eq.qaddr  = xive_end_qaddr(end);
435         /*
436          * The EQ toggle bit and index should only be relevant when
437          * restoring the EQ state
438          */
439         kvm_eq.qtoggle = xive_get_field32(END_W1_GENERATION, end->w1);
440         kvm_eq.qindex  = xive_get_field32(END_W1_PAGE_OFF, end->w1);
441     } else {
442         kvm_eq.qshift = 0;
443         kvm_eq.qaddr  = 0;
444     }
445 
446     /* Encode the tuple (server, prio) as a KVM EQ index */
447     spapr_xive_end_to_target(end_blk, end_idx, &server, &priority);
448 
449     kvm_eq_idx = priority << KVM_XIVE_EQ_PRIORITY_SHIFT &
450             KVM_XIVE_EQ_PRIORITY_MASK;
451     kvm_eq_idx |= server << KVM_XIVE_EQ_SERVER_SHIFT &
452         KVM_XIVE_EQ_SERVER_MASK;
453 
454     return
455         kvm_device_access(xive->fd, KVM_DEV_XIVE_GRP_EQ_CONFIG, kvm_eq_idx,
456                           &kvm_eq, true, errp);
457 }
458 
459 void kvmppc_xive_reset(SpaprXive *xive, Error **errp)
460 {
461     kvm_device_access(xive->fd, KVM_DEV_XIVE_GRP_CTRL, KVM_DEV_XIVE_RESET,
462                       NULL, true, errp);
463 }
464 
465 static int kvmppc_xive_get_queues(SpaprXive *xive, Error **errp)
466 {
467     int i;
468     int ret;
469 
470     for (i = 0; i < xive->nr_ends; i++) {
471         if (!xive_end_is_valid(&xive->endt[i])) {
472             continue;
473         }
474 
475         ret = kvmppc_xive_get_queue_config(xive, SPAPR_XIVE_BLOCK_ID, i,
476                                            &xive->endt[i], errp);
477         if (ret < 0) {
478             return ret;
479         }
480     }
481 
482     return 0;
483 }
484 
485 /*
486  * The primary goal of the XIVE VM change handler is to mark the EQ
487  * pages dirty when all XIVE event notifications have stopped.
488  *
489  * Whenever the VM is stopped, the VM change handler sets the source
490  * PQs to PENDING to stop the flow of events and to possibly catch a
491  * triggered interrupt occuring while the VM is stopped. The previous
492  * state is saved in anticipation of a migration. The XIVE controller
493  * is then synced through KVM to flush any in-flight event
494  * notification and stabilize the EQs.
495  *
496  * At this stage, we can mark the EQ page dirty and let a migration
497  * sequence transfer the EQ pages to the destination, which is done
498  * just after the stop state.
499  *
500  * The previous configuration of the sources is restored when the VM
501  * runs again. If an interrupt was queued while the VM was stopped,
502  * simply generate a trigger.
503  */
504 static void kvmppc_xive_change_state_handler(void *opaque, int running,
505                                              RunState state)
506 {
507     SpaprXive *xive = opaque;
508     XiveSource *xsrc = &xive->source;
509     Error *local_err = NULL;
510     int i;
511 
512     /*
513      * Restore the sources to their initial state. This is called when
514      * the VM resumes after a stop or a migration.
515      */
516     if (running) {
517         for (i = 0; i < xsrc->nr_irqs; i++) {
518             uint8_t pq;
519             uint8_t old_pq;
520 
521             if (!xive_eas_is_valid(&xive->eat[i])) {
522                 continue;
523             }
524 
525             pq = xive_source_esb_get(xsrc, i);
526             old_pq = xive_esb_read(xsrc, i, XIVE_ESB_SET_PQ_00 + (pq << 8));
527 
528             /*
529              * An interrupt was queued while the VM was stopped,
530              * generate a trigger.
531              */
532             if (pq == XIVE_ESB_RESET && old_pq == XIVE_ESB_QUEUED) {
533                 xive_esb_trigger(xsrc, i);
534             }
535         }
536 
537         return;
538     }
539 
540     /*
541      * Mask the sources, to stop the flow of event notifications, and
542      * save the PQs locally in the XiveSource object. The XiveSource
543      * state will be collected later on by its vmstate handler if a
544      * migration is in progress.
545      */
546     for (i = 0; i < xsrc->nr_irqs; i++) {
547         uint8_t pq;
548 
549         if (!xive_eas_is_valid(&xive->eat[i])) {
550             continue;
551         }
552 
553         pq = xive_esb_read(xsrc, i, XIVE_ESB_GET);
554 
555         /*
556          * PQ is set to PENDING to possibly catch a triggered
557          * interrupt occuring while the VM is stopped (hotplug event
558          * for instance) .
559          */
560         if (pq != XIVE_ESB_OFF) {
561             pq = xive_esb_read(xsrc, i, XIVE_ESB_SET_PQ_10);
562         }
563         xive_source_esb_set(xsrc, i, pq);
564     }
565 
566     /*
567      * Sync the XIVE controller in KVM, to flush in-flight event
568      * notification that should be enqueued in the EQs and mark the
569      * XIVE EQ pages dirty to collect all updates.
570      */
571     kvm_device_access(xive->fd, KVM_DEV_XIVE_GRP_CTRL,
572                       KVM_DEV_XIVE_EQ_SYNC, NULL, true, &local_err);
573     if (local_err) {
574         error_report_err(local_err);
575         return;
576     }
577 }
578 
579 void kvmppc_xive_synchronize_state(SpaprXive *xive, Error **errp)
580 {
581     assert(xive->fd != -1);
582 
583     /*
584      * When the VM is stopped, the sources are masked and the previous
585      * state is saved in anticipation of a migration. We should not
586      * synchronize the source state in that case else we will override
587      * the saved state.
588      */
589     if (runstate_is_running()) {
590         kvmppc_xive_source_get_state(&xive->source);
591     }
592 
593     /* EAT: there is no extra state to query from KVM */
594 
595     /* ENDT */
596     kvmppc_xive_get_queues(xive, errp);
597 }
598 
599 /*
600  * The SpaprXive 'pre_save' method is called by the vmstate handler of
601  * the SpaprXive model, after the XIVE controller is synced in the VM
602  * change handler.
603  */
604 int kvmppc_xive_pre_save(SpaprXive *xive)
605 {
606     Error *local_err = NULL;
607     int ret;
608 
609     assert(xive->fd != -1);
610 
611     /* EAT: there is no extra state to query from KVM */
612 
613     /* ENDT */
614     ret = kvmppc_xive_get_queues(xive, &local_err);
615     if (ret < 0) {
616         error_report_err(local_err);
617         return ret;
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 /* Returns MAP_FAILED on error and sets errno */
701 static void *kvmppc_xive_mmap(SpaprXive *xive, int pgoff, size_t len,
702                               Error **errp)
703 {
704     void *addr;
705     uint32_t page_shift = 16; /* TODO: fix page_shift */
706 
707     addr = mmap(NULL, len, PROT_WRITE | PROT_READ, MAP_SHARED, xive->fd,
708                 pgoff << page_shift);
709     if (addr == MAP_FAILED) {
710         error_setg_errno(errp, errno, "XIVE: unable to set memory mapping");
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     void *addr;
731 
732     /*
733      * The KVM XIVE device already in use. This is the case when
734      * rebooting under the XIVE-only interrupt mode.
735      */
736     if (xive->fd != -1) {
737         return 0;
738     }
739 
740     if (!kvmppc_has_cap_xive()) {
741         error_setg(errp, "IRQ_XIVE capability must be present for KVM");
742         return -1;
743     }
744 
745     /* First, create the KVM XIVE device */
746     fd = kvm_create_device(kvm_state, KVM_DEV_TYPE_XIVE, false);
747     if (fd < 0) {
748         error_setg_errno(errp, -fd, "XIVE: error creating KVM device");
749         return -1;
750     }
751     xive->fd = fd;
752 
753     /* Tell KVM about the # of VCPUs we may have */
754     if (kvm_device_check_attr(xive->fd, KVM_DEV_XIVE_GRP_CTRL,
755                               KVM_DEV_XIVE_NR_SERVERS)) {
756         if (kvm_device_access(xive->fd, KVM_DEV_XIVE_GRP_CTRL,
757                               KVM_DEV_XIVE_NR_SERVERS, &nr_servers, true,
758                               &local_err)) {
759             goto fail;
760         }
761     }
762 
763     /*
764      * 1. Source ESB pages - KVM mapping
765      */
766     addr = kvmppc_xive_mmap(xive, KVM_XIVE_ESB_PAGE_OFFSET, esb_len,
767                             &local_err);
768     if (addr == MAP_FAILED) {
769         goto fail;
770     }
771     xsrc->esb_mmap = addr;
772 
773     memory_region_init_ram_device_ptr(&xsrc->esb_mmio_kvm, OBJECT(xsrc),
774                                       "xive.esb-kvm", esb_len, xsrc->esb_mmap);
775     memory_region_add_subregion_overlap(&xsrc->esb_mmio, 0,
776                                         &xsrc->esb_mmio_kvm, 1);
777 
778     /*
779      * 2. END ESB pages (No KVM support yet)
780      */
781 
782     /*
783      * 3. TIMA pages - KVM mapping
784      */
785     addr = kvmppc_xive_mmap(xive, KVM_XIVE_TIMA_PAGE_OFFSET, tima_len,
786                             &local_err);
787     if (addr == MAP_FAILED) {
788         goto fail;
789     }
790     xive->tm_mmap = addr;
791 
792     memory_region_init_ram_device_ptr(&xive->tm_mmio_kvm, OBJECT(xive),
793                                       "xive.tima", tima_len, xive->tm_mmap);
794     memory_region_add_subregion_overlap(&xive->tm_mmio, 0,
795                                         &xive->tm_mmio_kvm, 1);
796 
797     xive->change = qemu_add_vm_change_state_handler(
798         kvmppc_xive_change_state_handler, xive);
799 
800     /* Connect the presenters to the initial VCPUs of the machine */
801     CPU_FOREACH(cs) {
802         PowerPCCPU *cpu = POWERPC_CPU(cs);
803 
804         kvmppc_xive_cpu_connect(spapr_cpu_state(cpu)->tctx, &local_err);
805         if (local_err) {
806             goto fail;
807         }
808     }
809 
810     /* Update the KVM sources */
811     kvmppc_xive_source_reset(xsrc, &local_err);
812     if (local_err) {
813         goto fail;
814     }
815 
816     kvm_kernel_irqchip = true;
817     kvm_msi_via_irqfd_allowed = true;
818     kvm_gsi_direct_mapping = true;
819     return 0;
820 
821 fail:
822     error_propagate(errp, local_err);
823     kvmppc_xive_disconnect(intc);
824     return -1;
825 }
826 
827 void kvmppc_xive_disconnect(SpaprInterruptController *intc)
828 {
829     SpaprXive *xive = SPAPR_XIVE(intc);
830     XiveSource *xsrc;
831     size_t esb_len;
832 
833     assert(xive->fd != -1);
834 
835     /* Clear the KVM mapping */
836     xsrc = &xive->source;
837     esb_len = (1ull << xsrc->esb_shift) * xsrc->nr_irqs;
838 
839     if (xsrc->esb_mmap) {
840         memory_region_del_subregion(&xsrc->esb_mmio, &xsrc->esb_mmio_kvm);
841         object_unparent(OBJECT(&xsrc->esb_mmio_kvm));
842         munmap(xsrc->esb_mmap, esb_len);
843         xsrc->esb_mmap = NULL;
844     }
845 
846     if (xive->tm_mmap) {
847         memory_region_del_subregion(&xive->tm_mmio, &xive->tm_mmio_kvm);
848         object_unparent(OBJECT(&xive->tm_mmio_kvm));
849         munmap(xive->tm_mmap, 4ull << TM_SHIFT);
850         xive->tm_mmap = NULL;
851     }
852 
853     /*
854      * When the KVM device fd is closed, the KVM device is destroyed
855      * and removed from the list of devices of the VM. The VCPU
856      * presenters are also detached from the device.
857      */
858     close(xive->fd);
859     xive->fd = -1;
860 
861     kvm_kernel_irqchip = false;
862     kvm_msi_via_irqfd_allowed = false;
863     kvm_gsi_direct_mapping = false;
864 
865     /* Clear the local list of presenter (hotplug) */
866     kvm_cpu_disable_all();
867 
868     /* VM Change state handler is not needed anymore */
869     if (xive->change) {
870         qemu_del_vm_change_state_handler(xive->change);
871         xive->change = NULL;
872     }
873 }
874