xref: /openbmc/qemu/hw/intc/spapr_xive_kvm.c (revision 135b03cb)
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_MACHINE(qdev_get_machine())->xive;
79     uint64_t state[2];
80     int ret;
81 
82     /* The KVM XIVE device is not in use yet */
83     if (xive->fd == -1) {
84         return;
85     }
86 
87     /* word0 and word1 of the OS ring. */
88     state[0] = *((uint64_t *) &tctx->regs[TM_QW1_OS]);
89 
90     ret = kvm_set_one_reg(tctx->cs, KVM_REG_PPC_VP_STATE, state);
91     if (ret != 0) {
92         error_setg_errno(errp, errno,
93                          "XIVE: could not restore KVM state of CPU %ld",
94                          kvm_arch_vcpu_id(tctx->cs));
95     }
96 }
97 
98 void kvmppc_xive_cpu_get_state(XiveTCTX *tctx, Error **errp)
99 {
100     SpaprXive *xive = SPAPR_MACHINE(qdev_get_machine())->xive;
101     uint64_t state[2] = { 0 };
102     int ret;
103 
104     /* The KVM XIVE device is not in use */
105     if (xive->fd == -1) {
106         return;
107     }
108 
109     ret = kvm_get_one_reg(tctx->cs, KVM_REG_PPC_VP_STATE, state);
110     if (ret != 0) {
111         error_setg_errno(errp, errno,
112                          "XIVE: could not capture KVM state of CPU %ld",
113                          kvm_arch_vcpu_id(tctx->cs));
114         return;
115     }
116 
117     /* word0 and word1 of the OS ring. */
118     *((uint64_t *) &tctx->regs[TM_QW1_OS]) = state[0];
119 }
120 
121 typedef struct {
122     XiveTCTX *tctx;
123     Error *err;
124 } XiveCpuGetState;
125 
126 static void kvmppc_xive_cpu_do_synchronize_state(CPUState *cpu,
127                                                  run_on_cpu_data arg)
128 {
129     XiveCpuGetState *s = arg.host_ptr;
130 
131     kvmppc_xive_cpu_get_state(s->tctx, &s->err);
132 }
133 
134 void kvmppc_xive_cpu_synchronize_state(XiveTCTX *tctx, Error **errp)
135 {
136     XiveCpuGetState s = {
137         .tctx = tctx,
138         .err = NULL,
139     };
140 
141     /*
142      * Kick the vCPU to make sure they are available for the KVM ioctl.
143      */
144     run_on_cpu(tctx->cs, kvmppc_xive_cpu_do_synchronize_state,
145                RUN_ON_CPU_HOST_PTR(&s));
146 
147     if (s.err) {
148         error_propagate(errp, s.err);
149         return;
150     }
151 }
152 
153 void kvmppc_xive_cpu_connect(XiveTCTX *tctx, Error **errp)
154 {
155     SpaprXive *xive = SPAPR_MACHINE(qdev_get_machine())->xive;
156     unsigned long vcpu_id;
157     int ret;
158 
159     /* The KVM XIVE device is not in use */
160     if (xive->fd == -1) {
161         return;
162     }
163 
164     /* Check if CPU was hot unplugged and replugged. */
165     if (kvm_cpu_is_enabled(tctx->cs)) {
166         return;
167     }
168 
169     vcpu_id = kvm_arch_vcpu_id(tctx->cs);
170 
171     ret = kvm_vcpu_enable_cap(tctx->cs, KVM_CAP_PPC_IRQ_XIVE, 0, xive->fd,
172                               vcpu_id, 0);
173     if (ret < 0) {
174         error_setg(errp, "XIVE: unable to connect CPU%ld to KVM device: %s",
175                    vcpu_id, strerror(errno));
176         return;
177     }
178 
179     kvm_cpu_enable(tctx->cs);
180 }
181 
182 /*
183  * XIVE Interrupt Source (KVM)
184  */
185 
186 void kvmppc_xive_set_source_config(SpaprXive *xive, uint32_t lisn, XiveEAS *eas,
187                                    Error **errp)
188 {
189     uint32_t end_idx;
190     uint32_t end_blk;
191     uint8_t priority;
192     uint32_t server;
193     bool masked;
194     uint32_t eisn;
195     uint64_t kvm_src;
196     Error *local_err = NULL;
197 
198     assert(xive_eas_is_valid(eas));
199 
200     end_idx = xive_get_field64(EAS_END_INDEX, eas->w);
201     end_blk = xive_get_field64(EAS_END_BLOCK, eas->w);
202     eisn = xive_get_field64(EAS_END_DATA, eas->w);
203     masked = xive_eas_is_masked(eas);
204 
205     spapr_xive_end_to_target(end_blk, end_idx, &server, &priority);
206 
207     kvm_src = priority << KVM_XIVE_SOURCE_PRIORITY_SHIFT &
208         KVM_XIVE_SOURCE_PRIORITY_MASK;
209     kvm_src |= server << KVM_XIVE_SOURCE_SERVER_SHIFT &
210         KVM_XIVE_SOURCE_SERVER_MASK;
211     kvm_src |= ((uint64_t) masked << KVM_XIVE_SOURCE_MASKED_SHIFT) &
212         KVM_XIVE_SOURCE_MASKED_MASK;
213     kvm_src |= ((uint64_t)eisn << KVM_XIVE_SOURCE_EISN_SHIFT) &
214         KVM_XIVE_SOURCE_EISN_MASK;
215 
216     kvm_device_access(xive->fd, KVM_DEV_XIVE_GRP_SOURCE_CONFIG, lisn,
217                       &kvm_src, true, &local_err);
218     if (local_err) {
219         error_propagate(errp, local_err);
220         return;
221     }
222 }
223 
224 void kvmppc_xive_sync_source(SpaprXive *xive, uint32_t lisn, Error **errp)
225 {
226     kvm_device_access(xive->fd, KVM_DEV_XIVE_GRP_SOURCE_SYNC, lisn,
227                       NULL, true, errp);
228 }
229 
230 /*
231  * At reset, the interrupt sources are simply created and MASKED. We
232  * only need to inform the KVM XIVE device about their type: LSI or
233  * MSI.
234  */
235 void kvmppc_xive_source_reset_one(XiveSource *xsrc, int srcno, Error **errp)
236 {
237     SpaprXive *xive = SPAPR_XIVE(xsrc->xive);
238     uint64_t state = 0;
239 
240     /* The KVM XIVE device is not in use */
241     if (xive->fd == -1) {
242         return;
243     }
244 
245     if (xive_source_irq_is_lsi(xsrc, srcno)) {
246         state |= KVM_XIVE_LEVEL_SENSITIVE;
247         if (xsrc->status[srcno] & XIVE_STATUS_ASSERTED) {
248             state |= KVM_XIVE_LEVEL_ASSERTED;
249         }
250     }
251 
252     kvm_device_access(xive->fd, KVM_DEV_XIVE_GRP_SOURCE, srcno, &state,
253                       true, errp);
254 }
255 
256 static void kvmppc_xive_source_reset(XiveSource *xsrc, Error **errp)
257 {
258     int i;
259 
260     for (i = 0; i < xsrc->nr_irqs; i++) {
261         Error *local_err = NULL;
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     int i;
332 
333     for (i = 0; i < xsrc->nr_irqs; i++) {
334         /* Perform a load without side effect to retrieve the PQ bits */
335         uint8_t pq = xive_esb_read(xsrc, i, XIVE_ESB_GET);
336 
337         /* and save PQ locally */
338         xive_source_esb_set(xsrc, i, pq);
339     }
340 }
341 
342 void kvmppc_xive_source_set_irq(void *opaque, int srcno, int val)
343 {
344     XiveSource *xsrc = opaque;
345     SpaprXive *xive = SPAPR_XIVE(xsrc->xive);
346     struct kvm_irq_level args;
347     int rc;
348 
349     /* The KVM XIVE device should be in use */
350     assert(xive->fd != -1);
351 
352     args.irq = srcno;
353     if (!xive_source_irq_is_lsi(xsrc, srcno)) {
354         if (!val) {
355             return;
356         }
357         args.level = KVM_INTERRUPT_SET;
358     } else {
359         if (val) {
360             xsrc->status[srcno] |= XIVE_STATUS_ASSERTED;
361             args.level = KVM_INTERRUPT_SET_LEVEL;
362         } else {
363             xsrc->status[srcno] &= ~XIVE_STATUS_ASSERTED;
364             args.level = KVM_INTERRUPT_UNSET;
365         }
366     }
367     rc = kvm_vm_ioctl(kvm_state, KVM_IRQ_LINE, &args);
368     if (rc < 0) {
369         error_report("XIVE: kvm_irq_line() failed : %s", strerror(errno));
370     }
371 }
372 
373 /*
374  * sPAPR XIVE interrupt controller (KVM)
375  */
376 void kvmppc_xive_get_queue_config(SpaprXive *xive, uint8_t end_blk,
377                                   uint32_t end_idx, XiveEND *end,
378                                   Error **errp)
379 {
380     struct kvm_ppc_xive_eq kvm_eq = { 0 };
381     uint64_t kvm_eq_idx;
382     uint8_t priority;
383     uint32_t server;
384     Error *local_err = NULL;
385 
386     assert(xive_end_is_valid(end));
387 
388     /* Encode the tuple (server, prio) as a KVM EQ index */
389     spapr_xive_end_to_target(end_blk, end_idx, &server, &priority);
390 
391     kvm_eq_idx = priority << KVM_XIVE_EQ_PRIORITY_SHIFT &
392             KVM_XIVE_EQ_PRIORITY_MASK;
393     kvm_eq_idx |= server << KVM_XIVE_EQ_SERVER_SHIFT &
394         KVM_XIVE_EQ_SERVER_MASK;
395 
396     kvm_device_access(xive->fd, KVM_DEV_XIVE_GRP_EQ_CONFIG, kvm_eq_idx,
397                       &kvm_eq, false, &local_err);
398     if (local_err) {
399         error_propagate(errp, local_err);
400         return;
401     }
402 
403     /*
404      * The EQ index and toggle bit are updated by HW. These are the
405      * only fields from KVM we want to update QEMU with. The other END
406      * fields should already be in the QEMU END table.
407      */
408     end->w1 = xive_set_field32(END_W1_GENERATION, 0ul, kvm_eq.qtoggle) |
409         xive_set_field32(END_W1_PAGE_OFF, 0ul, kvm_eq.qindex);
410 }
411 
412 void kvmppc_xive_set_queue_config(SpaprXive *xive, uint8_t end_blk,
413                                   uint32_t end_idx, XiveEND *end,
414                                   Error **errp)
415 {
416     struct kvm_ppc_xive_eq kvm_eq = { 0 };
417     uint64_t kvm_eq_idx;
418     uint8_t priority;
419     uint32_t server;
420     Error *local_err = NULL;
421 
422     /*
423      * Build the KVM state from the local END structure.
424      */
425 
426     kvm_eq.flags = 0;
427     if (xive_get_field32(END_W0_UCOND_NOTIFY, end->w0)) {
428         kvm_eq.flags |= KVM_XIVE_EQ_ALWAYS_NOTIFY;
429     }
430 
431     /*
432      * If the hcall is disabling the EQ, set the size and page address
433      * to zero. When migrating, only valid ENDs are taken into
434      * account.
435      */
436     if (xive_end_is_valid(end)) {
437         kvm_eq.qshift = xive_get_field32(END_W0_QSIZE, end->w0) + 12;
438         kvm_eq.qaddr  = xive_end_qaddr(end);
439         /*
440          * The EQ toggle bit and index should only be relevant when
441          * restoring the EQ state
442          */
443         kvm_eq.qtoggle = xive_get_field32(END_W1_GENERATION, end->w1);
444         kvm_eq.qindex  = xive_get_field32(END_W1_PAGE_OFF, end->w1);
445     } else {
446         kvm_eq.qshift = 0;
447         kvm_eq.qaddr  = 0;
448     }
449 
450     /* Encode the tuple (server, prio) as a KVM EQ index */
451     spapr_xive_end_to_target(end_blk, end_idx, &server, &priority);
452 
453     kvm_eq_idx = priority << KVM_XIVE_EQ_PRIORITY_SHIFT &
454             KVM_XIVE_EQ_PRIORITY_MASK;
455     kvm_eq_idx |= server << KVM_XIVE_EQ_SERVER_SHIFT &
456         KVM_XIVE_EQ_SERVER_MASK;
457 
458     kvm_device_access(xive->fd, KVM_DEV_XIVE_GRP_EQ_CONFIG, kvm_eq_idx,
459                       &kvm_eq, true, &local_err);
460     if (local_err) {
461         error_propagate(errp, local_err);
462         return;
463     }
464 }
465 
466 void kvmppc_xive_reset(SpaprXive *xive, Error **errp)
467 {
468     kvm_device_access(xive->fd, KVM_DEV_XIVE_GRP_CTRL, KVM_DEV_XIVE_RESET,
469                       NULL, true, errp);
470 }
471 
472 static void kvmppc_xive_get_queues(SpaprXive *xive, Error **errp)
473 {
474     Error *local_err = NULL;
475     int i;
476 
477     for (i = 0; i < xive->nr_ends; i++) {
478         if (!xive_end_is_valid(&xive->endt[i])) {
479             continue;
480         }
481 
482         kvmppc_xive_get_queue_config(xive, SPAPR_XIVE_BLOCK_ID, i,
483                                      &xive->endt[i], &local_err);
484         if (local_err) {
485             error_propagate(errp, local_err);
486             return;
487         }
488     }
489 }
490 
491 /*
492  * The primary goal of the XIVE VM change handler is to mark the EQ
493  * pages dirty when all XIVE event notifications have stopped.
494  *
495  * Whenever the VM is stopped, the VM change handler sets the source
496  * PQs to PENDING to stop the flow of events and to possibly catch a
497  * triggered interrupt occuring while the VM is stopped. The previous
498  * state is saved in anticipation of a migration. The XIVE controller
499  * is then synced through KVM to flush any in-flight event
500  * notification and stabilize the EQs.
501  *
502  * At this stage, we can mark the EQ page dirty and let a migration
503  * sequence transfer the EQ pages to the destination, which is done
504  * just after the stop state.
505  *
506  * The previous configuration of the sources is restored when the VM
507  * runs again. If an interrupt was queued while the VM was stopped,
508  * simply generate a trigger.
509  */
510 static void kvmppc_xive_change_state_handler(void *opaque, int running,
511                                              RunState state)
512 {
513     SpaprXive *xive = opaque;
514     XiveSource *xsrc = &xive->source;
515     Error *local_err = NULL;
516     int i;
517 
518     /*
519      * Restore the sources to their initial state. This is called when
520      * the VM resumes after a stop or a migration.
521      */
522     if (running) {
523         for (i = 0; i < xsrc->nr_irqs; i++) {
524             uint8_t pq = xive_source_esb_get(xsrc, i);
525             uint8_t old_pq;
526 
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 = xive_esb_read(xsrc, i, XIVE_ESB_GET);
549 
550         /*
551          * PQ is set to PENDING to possibly catch a triggered
552          * interrupt occuring while the VM is stopped (hotplug event
553          * for instance) .
554          */
555         if (pq != XIVE_ESB_OFF) {
556             pq = xive_esb_read(xsrc, i, XIVE_ESB_SET_PQ_10);
557         }
558         xive_source_esb_set(xsrc, i, pq);
559     }
560 
561     /*
562      * Sync the XIVE controller in KVM, to flush in-flight event
563      * notification that should be enqueued in the EQs and mark the
564      * XIVE EQ pages dirty to collect all updates.
565      */
566     kvm_device_access(xive->fd, KVM_DEV_XIVE_GRP_CTRL,
567                       KVM_DEV_XIVE_EQ_SYNC, NULL, true, &local_err);
568     if (local_err) {
569         error_report_err(local_err);
570         return;
571     }
572 }
573 
574 void kvmppc_xive_synchronize_state(SpaprXive *xive, Error **errp)
575 {
576     /* The KVM XIVE device is not in use */
577     if (xive->fd == -1) {
578         return;
579     }
580 
581     /*
582      * When the VM is stopped, the sources are masked and the previous
583      * state is saved in anticipation of a migration. We should not
584      * synchronize the source state in that case else we will override
585      * the saved state.
586      */
587     if (runstate_is_running()) {
588         kvmppc_xive_source_get_state(&xive->source);
589     }
590 
591     /* EAT: there is no extra state to query from KVM */
592 
593     /* ENDT */
594     kvmppc_xive_get_queues(xive, errp);
595 }
596 
597 /*
598  * The SpaprXive 'pre_save' method is called by the vmstate handler of
599  * the SpaprXive model, after the XIVE controller is synced in the VM
600  * change handler.
601  */
602 int kvmppc_xive_pre_save(SpaprXive *xive)
603 {
604     Error *local_err = NULL;
605 
606     /* The KVM XIVE device is not in use */
607     if (xive->fd == -1) {
608         return 0;
609     }
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         kvmppc_xive_set_source_config(xive, i, &xive->eat[i], &local_err);
659         if (local_err) {
660             error_report_err(local_err);
661             return -1;
662         }
663     }
664 
665     /*
666      * Restore the thread interrupt contexts of initial CPUs.
667      *
668      * The context of hotplugged CPUs is restored later, by the
669      * 'post_load' handler of the XiveTCTX model because they are not
670      * available at the time the SpaprXive 'post_load' method is
671      * called. We can not restore the context of all CPUs in the
672      * 'post_load' handler of XiveTCTX because the machine is not
673      * necessarily connected to the KVM device at that time.
674      */
675     CPU_FOREACH(cs) {
676         PowerPCCPU *cpu = POWERPC_CPU(cs);
677 
678         kvmppc_xive_cpu_set_state(spapr_cpu_state(cpu)->tctx, &local_err);
679         if (local_err) {
680             error_report_err(local_err);
681             return -1;
682         }
683     }
684 
685     /* The source states will be restored when the machine starts running */
686     return 0;
687 }
688 
689 static void *kvmppc_xive_mmap(SpaprXive *xive, int pgoff, size_t len,
690                               Error **errp)
691 {
692     void *addr;
693     uint32_t page_shift = 16; /* TODO: fix page_shift */
694 
695     addr = mmap(NULL, len, PROT_WRITE | PROT_READ, MAP_SHARED, xive->fd,
696                 pgoff << page_shift);
697     if (addr == MAP_FAILED) {
698         error_setg_errno(errp, errno, "XIVE: unable to set memory mapping");
699         return NULL;
700     }
701 
702     return addr;
703 }
704 
705 /*
706  * All the XIVE memory regions are now backed by mappings from the KVM
707  * XIVE device.
708  */
709 void kvmppc_xive_connect(SpaprXive *xive, Error **errp)
710 {
711     XiveSource *xsrc = &xive->source;
712     Error *local_err = NULL;
713     size_t esb_len = (1ull << xsrc->esb_shift) * xsrc->nr_irqs;
714     size_t tima_len = 4ull << TM_SHIFT;
715     CPUState *cs;
716 
717     /*
718      * The KVM XIVE device already in use. This is the case when
719      * rebooting under the XIVE-only interrupt mode.
720      */
721     if (xive->fd != -1) {
722         return;
723     }
724 
725     if (!kvmppc_has_cap_xive()) {
726         error_setg(errp, "IRQ_XIVE capability must be present for KVM");
727         return;
728     }
729 
730     /* First, create the KVM XIVE device */
731     xive->fd = kvm_create_device(kvm_state, KVM_DEV_TYPE_XIVE, false);
732     if (xive->fd < 0) {
733         error_setg_errno(errp, -xive->fd, "XIVE: error creating KVM device");
734         return;
735     }
736 
737     /*
738      * 1. Source ESB pages - KVM mapping
739      */
740     xsrc->esb_mmap = kvmppc_xive_mmap(xive, KVM_XIVE_ESB_PAGE_OFFSET, esb_len,
741                                       &local_err);
742     if (local_err) {
743         goto fail;
744     }
745 
746     memory_region_init_ram_device_ptr(&xsrc->esb_mmio_kvm, OBJECT(xsrc),
747                                       "xive.esb", esb_len, xsrc->esb_mmap);
748     memory_region_add_subregion_overlap(&xsrc->esb_mmio, 0,
749                                         &xsrc->esb_mmio_kvm, 1);
750 
751     /*
752      * 2. END ESB pages (No KVM support yet)
753      */
754 
755     /*
756      * 3. TIMA pages - KVM mapping
757      */
758     xive->tm_mmap = kvmppc_xive_mmap(xive, KVM_XIVE_TIMA_PAGE_OFFSET, tima_len,
759                                      &local_err);
760     if (local_err) {
761         goto fail;
762     }
763     memory_region_init_ram_device_ptr(&xive->tm_mmio_kvm, OBJECT(xive),
764                                       "xive.tima", tima_len, xive->tm_mmap);
765     memory_region_add_subregion_overlap(&xive->tm_mmio, 0,
766                                         &xive->tm_mmio_kvm, 1);
767 
768     xive->change = qemu_add_vm_change_state_handler(
769         kvmppc_xive_change_state_handler, xive);
770 
771     /* Connect the presenters to the initial VCPUs of the machine */
772     CPU_FOREACH(cs) {
773         PowerPCCPU *cpu = POWERPC_CPU(cs);
774 
775         kvmppc_xive_cpu_connect(spapr_cpu_state(cpu)->tctx, &local_err);
776         if (local_err) {
777             goto fail;
778         }
779     }
780 
781     /* Update the KVM sources */
782     kvmppc_xive_source_reset(xsrc, &local_err);
783     if (local_err) {
784         goto fail;
785     }
786 
787     kvm_kernel_irqchip = true;
788     kvm_msi_via_irqfd_allowed = true;
789     kvm_gsi_direct_mapping = true;
790     return;
791 
792 fail:
793     error_propagate(errp, local_err);
794     kvmppc_xive_disconnect(xive, NULL);
795 }
796 
797 void kvmppc_xive_disconnect(SpaprXive *xive, Error **errp)
798 {
799     XiveSource *xsrc;
800     size_t esb_len;
801 
802     /* The KVM XIVE device is not in use */
803     if (!xive || xive->fd == -1) {
804         return;
805     }
806 
807     if (!kvmppc_has_cap_xive()) {
808         error_setg(errp, "IRQ_XIVE capability must be present for KVM");
809         return;
810     }
811 
812     /* Clear the KVM mapping */
813     xsrc = &xive->source;
814     esb_len = (1ull << xsrc->esb_shift) * xsrc->nr_irqs;
815 
816     if (xsrc->esb_mmap) {
817         memory_region_del_subregion(&xsrc->esb_mmio, &xsrc->esb_mmio_kvm);
818         object_unparent(OBJECT(&xsrc->esb_mmio_kvm));
819         munmap(xsrc->esb_mmap, esb_len);
820         xsrc->esb_mmap = NULL;
821     }
822 
823     if (xive->tm_mmap) {
824         memory_region_del_subregion(&xive->tm_mmio, &xive->tm_mmio_kvm);
825         object_unparent(OBJECT(&xive->tm_mmio_kvm));
826         munmap(xive->tm_mmap, 4ull << TM_SHIFT);
827         xive->tm_mmap = NULL;
828     }
829 
830     /*
831      * When the KVM device fd is closed, the KVM device is destroyed
832      * and removed from the list of devices of the VM. The VCPU
833      * presenters are also detached from the device.
834      */
835     if (xive->fd != -1) {
836         close(xive->fd);
837         xive->fd = -1;
838     }
839 
840     kvm_kernel_irqchip = false;
841     kvm_msi_via_irqfd_allowed = false;
842     kvm_gsi_direct_mapping = false;
843 
844     /* Clear the local list of presenter (hotplug) */
845     kvm_cpu_disable_all();
846 
847     /* VM Change state handler is not needed anymore */
848     if (xive->change) {
849         qemu_del_vm_change_state_handler(xive->change);
850         xive->change = NULL;
851     }
852 }
853