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