xref: /qemu/hw/intc/spapr_xive.c (revision 292743d9)
1 /*
2  * QEMU PowerPC sPAPR XIVE interrupt controller model
3  *
4  * Copyright (c) 2017-2018, 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/module.h"
13 #include "qapi/error.h"
14 #include "qemu/error-report.h"
15 #include "target/ppc/cpu.h"
16 #include "sysemu/cpus.h"
17 #include "sysemu/reset.h"
18 #include "migration/vmstate.h"
19 #include "monitor/monitor.h"
20 #include "hw/ppc/fdt.h"
21 #include "hw/ppc/spapr.h"
22 #include "hw/ppc/spapr_cpu_core.h"
23 #include "hw/ppc/spapr_xive.h"
24 #include "hw/ppc/xive.h"
25 #include "hw/ppc/xive_regs.h"
26 #include "hw/qdev-properties.h"
27 
28 /*
29  * XIVE Virtualization Controller BAR and Thread Managment BAR that we
30  * use for the ESB pages and the TIMA pages
31  */
32 #define SPAPR_XIVE_VC_BASE   0x0006010000000000ull
33 #define SPAPR_XIVE_TM_BASE   0x0006030203180000ull
34 
35 /*
36  * The allocation of VP blocks is a complex operation in OPAL and the
37  * VP identifiers have a relation with the number of HW chips, the
38  * size of the VP blocks, VP grouping, etc. The QEMU sPAPR XIVE
39  * controller model does not have the same constraints and can use a
40  * simple mapping scheme of the CPU vcpu_id
41  *
42  * These identifiers are never returned to the OS.
43  */
44 
45 #define SPAPR_XIVE_NVT_BASE 0x400
46 
47 /*
48  * sPAPR NVT and END indexing helpers
49  */
50 static uint32_t spapr_xive_nvt_to_target(uint8_t nvt_blk, uint32_t nvt_idx)
51 {
52     return nvt_idx - SPAPR_XIVE_NVT_BASE;
53 }
54 
55 static void spapr_xive_cpu_to_nvt(PowerPCCPU *cpu,
56                                   uint8_t *out_nvt_blk, uint32_t *out_nvt_idx)
57 {
58     assert(cpu);
59 
60     if (out_nvt_blk) {
61         *out_nvt_blk = SPAPR_XIVE_BLOCK_ID;
62     }
63 
64     if (out_nvt_blk) {
65         *out_nvt_idx = SPAPR_XIVE_NVT_BASE + cpu->vcpu_id;
66     }
67 }
68 
69 static int spapr_xive_target_to_nvt(uint32_t target,
70                                     uint8_t *out_nvt_blk, uint32_t *out_nvt_idx)
71 {
72     PowerPCCPU *cpu = spapr_find_cpu(target);
73 
74     if (!cpu) {
75         return -1;
76     }
77 
78     spapr_xive_cpu_to_nvt(cpu, out_nvt_blk, out_nvt_idx);
79     return 0;
80 }
81 
82 /*
83  * sPAPR END indexing uses a simple mapping of the CPU vcpu_id, 8
84  * priorities per CPU
85  */
86 int spapr_xive_end_to_target(uint8_t end_blk, uint32_t end_idx,
87                              uint32_t *out_server, uint8_t *out_prio)
88 {
89 
90     assert(end_blk == SPAPR_XIVE_BLOCK_ID);
91 
92     if (out_server) {
93         *out_server = end_idx >> 3;
94     }
95 
96     if (out_prio) {
97         *out_prio = end_idx & 0x7;
98     }
99     return 0;
100 }
101 
102 static void spapr_xive_cpu_to_end(PowerPCCPU *cpu, uint8_t prio,
103                                   uint8_t *out_end_blk, uint32_t *out_end_idx)
104 {
105     assert(cpu);
106 
107     if (out_end_blk) {
108         *out_end_blk = SPAPR_XIVE_BLOCK_ID;
109     }
110 
111     if (out_end_idx) {
112         *out_end_idx = (cpu->vcpu_id << 3) + prio;
113     }
114 }
115 
116 static int spapr_xive_target_to_end(uint32_t target, uint8_t prio,
117                                     uint8_t *out_end_blk, uint32_t *out_end_idx)
118 {
119     PowerPCCPU *cpu = spapr_find_cpu(target);
120 
121     if (!cpu) {
122         return -1;
123     }
124 
125     spapr_xive_cpu_to_end(cpu, prio, out_end_blk, out_end_idx);
126     return 0;
127 }
128 
129 /*
130  * On sPAPR machines, use a simplified output for the XIVE END
131  * structure dumping only the information related to the OS EQ.
132  */
133 static void spapr_xive_end_pic_print_info(SpaprXive *xive, XiveEND *end,
134                                           Monitor *mon)
135 {
136     uint64_t qaddr_base = xive_end_qaddr(end);
137     uint32_t qindex = xive_get_field32(END_W1_PAGE_OFF, end->w1);
138     uint32_t qgen = xive_get_field32(END_W1_GENERATION, end->w1);
139     uint32_t qsize = xive_get_field32(END_W0_QSIZE, end->w0);
140     uint32_t qentries = 1 << (qsize + 10);
141     uint32_t nvt = xive_get_field32(END_W6_NVT_INDEX, end->w6);
142     uint8_t priority = xive_get_field32(END_W7_F0_PRIORITY, end->w7);
143 
144     monitor_printf(mon, "%3d/%d % 6d/%5d @%"PRIx64" ^%d",
145                    spapr_xive_nvt_to_target(0, nvt),
146                    priority, qindex, qentries, qaddr_base, qgen);
147 
148     xive_end_queue_pic_print_info(end, 6, mon);
149 }
150 
151 void spapr_xive_pic_print_info(SpaprXive *xive, Monitor *mon)
152 {
153     XiveSource *xsrc = &xive->source;
154     int i;
155 
156     if (kvm_irqchip_in_kernel()) {
157         Error *local_err = NULL;
158 
159         kvmppc_xive_synchronize_state(xive, &local_err);
160         if (local_err) {
161             error_report_err(local_err);
162             return;
163         }
164     }
165 
166     monitor_printf(mon, "  LISN         PQ    EISN     CPU/PRIO EQ\n");
167 
168     for (i = 0; i < xive->nr_irqs; i++) {
169         uint8_t pq = xive_source_esb_get(xsrc, i);
170         XiveEAS *eas = &xive->eat[i];
171 
172         if (!xive_eas_is_valid(eas)) {
173             continue;
174         }
175 
176         monitor_printf(mon, "  %08x %s %c%c%c %s %08x ", i,
177                        xive_source_irq_is_lsi(xsrc, i) ? "LSI" : "MSI",
178                        pq & XIVE_ESB_VAL_P ? 'P' : '-',
179                        pq & XIVE_ESB_VAL_Q ? 'Q' : '-',
180                        xsrc->status[i] & XIVE_STATUS_ASSERTED ? 'A' : ' ',
181                        xive_eas_is_masked(eas) ? "M" : " ",
182                        (int) xive_get_field64(EAS_END_DATA, eas->w));
183 
184         if (!xive_eas_is_masked(eas)) {
185             uint32_t end_idx = xive_get_field64(EAS_END_INDEX, eas->w);
186             XiveEND *end;
187 
188             assert(end_idx < xive->nr_ends);
189             end = &xive->endt[end_idx];
190 
191             if (xive_end_is_valid(end)) {
192                 spapr_xive_end_pic_print_info(xive, end, mon);
193             }
194         }
195         monitor_printf(mon, "\n");
196     }
197 }
198 
199 void spapr_xive_mmio_set_enabled(SpaprXive *xive, bool enable)
200 {
201     memory_region_set_enabled(&xive->source.esb_mmio, enable);
202     memory_region_set_enabled(&xive->tm_mmio, enable);
203 
204     /* Disable the END ESBs until a guest OS makes use of them */
205     memory_region_set_enabled(&xive->end_source.esb_mmio, false);
206 }
207 
208 static void spapr_xive_tm_write(void *opaque, hwaddr offset,
209                           uint64_t value, unsigned size)
210 {
211     XiveTCTX *tctx = spapr_cpu_state(POWERPC_CPU(current_cpu))->tctx;
212 
213     xive_tctx_tm_write(XIVE_PRESENTER(opaque), tctx, offset, value, size);
214 }
215 
216 static uint64_t spapr_xive_tm_read(void *opaque, hwaddr offset, unsigned size)
217 {
218     XiveTCTX *tctx = spapr_cpu_state(POWERPC_CPU(current_cpu))->tctx;
219 
220     return xive_tctx_tm_read(XIVE_PRESENTER(opaque), tctx, offset, size);
221 }
222 
223 const MemoryRegionOps spapr_xive_tm_ops = {
224     .read = spapr_xive_tm_read,
225     .write = spapr_xive_tm_write,
226     .endianness = DEVICE_BIG_ENDIAN,
227     .valid = {
228         .min_access_size = 1,
229         .max_access_size = 8,
230     },
231     .impl = {
232         .min_access_size = 1,
233         .max_access_size = 8,
234     },
235 };
236 
237 static void spapr_xive_end_reset(XiveEND *end)
238 {
239     memset(end, 0, sizeof(*end));
240 
241     /* switch off the escalation and notification ESBs */
242     end->w1 = cpu_to_be32(END_W1_ESe_Q | END_W1_ESn_Q);
243 }
244 
245 static void spapr_xive_reset(void *dev)
246 {
247     SpaprXive *xive = SPAPR_XIVE(dev);
248     int i;
249 
250     /*
251      * The XiveSource has its own reset handler, which mask off all
252      * IRQs (!P|Q)
253      */
254 
255     /* Mask all valid EASs in the IRQ number space. */
256     for (i = 0; i < xive->nr_irqs; i++) {
257         XiveEAS *eas = &xive->eat[i];
258         if (xive_eas_is_valid(eas)) {
259             eas->w = cpu_to_be64(EAS_VALID | EAS_MASKED);
260         } else {
261             eas->w = 0;
262         }
263     }
264 
265     /* Clear all ENDs */
266     for (i = 0; i < xive->nr_ends; i++) {
267         spapr_xive_end_reset(&xive->endt[i]);
268     }
269 }
270 
271 static void spapr_xive_instance_init(Object *obj)
272 {
273     SpaprXive *xive = SPAPR_XIVE(obj);
274 
275     object_initialize_child(obj, "source", &xive->source, sizeof(xive->source),
276                             TYPE_XIVE_SOURCE, &error_abort, NULL);
277 
278     object_initialize_child(obj, "end_source", &xive->end_source,
279                             sizeof(xive->end_source), TYPE_XIVE_END_SOURCE,
280                             &error_abort, NULL);
281 
282     /* Not connected to the KVM XIVE device */
283     xive->fd = -1;
284 }
285 
286 static void spapr_xive_realize(DeviceState *dev, Error **errp)
287 {
288     SpaprXive *xive = SPAPR_XIVE(dev);
289     XiveSource *xsrc = &xive->source;
290     XiveENDSource *end_xsrc = &xive->end_source;
291     Error *local_err = NULL;
292 
293     if (!xive->nr_irqs) {
294         error_setg(errp, "Number of interrupt needs to be greater 0");
295         return;
296     }
297 
298     if (!xive->nr_ends) {
299         error_setg(errp, "Number of interrupt needs to be greater 0");
300         return;
301     }
302 
303     /*
304      * Initialize the internal sources, for IPIs and virtual devices.
305      */
306     object_property_set_int(OBJECT(xsrc), xive->nr_irqs, "nr-irqs",
307                             &error_fatal);
308     object_property_set_link(OBJECT(xsrc), OBJECT(xive), "xive",
309                              &error_abort);
310     object_property_set_bool(OBJECT(xsrc), true, "realized", &local_err);
311     if (local_err) {
312         error_propagate(errp, local_err);
313         return;
314     }
315     sysbus_init_mmio(SYS_BUS_DEVICE(xive), &xsrc->esb_mmio);
316 
317     /*
318      * Initialize the END ESB source
319      */
320     object_property_set_int(OBJECT(end_xsrc), xive->nr_irqs, "nr-ends",
321                             &error_fatal);
322     object_property_set_link(OBJECT(end_xsrc), OBJECT(xive), "xive",
323                              &error_abort);
324     object_property_set_bool(OBJECT(end_xsrc), true, "realized", &local_err);
325     if (local_err) {
326         error_propagate(errp, local_err);
327         return;
328     }
329     sysbus_init_mmio(SYS_BUS_DEVICE(xive), &end_xsrc->esb_mmio);
330 
331     /* Set the mapping address of the END ESB pages after the source ESBs */
332     xive->end_base = xive->vc_base + (1ull << xsrc->esb_shift) * xsrc->nr_irqs;
333 
334     /*
335      * Allocate the routing tables
336      */
337     xive->eat = g_new0(XiveEAS, xive->nr_irqs);
338     xive->endt = g_new0(XiveEND, xive->nr_ends);
339 
340     xive->nodename = g_strdup_printf("interrupt-controller@%" PRIx64,
341                            xive->tm_base + XIVE_TM_USER_PAGE * (1 << TM_SHIFT));
342 
343     qemu_register_reset(spapr_xive_reset, dev);
344 
345     /* TIMA initialization */
346     memory_region_init_io(&xive->tm_mmio, OBJECT(xive), &spapr_xive_tm_ops,
347                           xive, "xive.tima", 4ull << TM_SHIFT);
348     sysbus_init_mmio(SYS_BUS_DEVICE(xive), &xive->tm_mmio);
349 
350     /*
351      * Map all regions. These will be enabled or disabled at reset and
352      * can also be overridden by KVM memory regions if active
353      */
354     sysbus_mmio_map(SYS_BUS_DEVICE(xive), 0, xive->vc_base);
355     sysbus_mmio_map(SYS_BUS_DEVICE(xive), 1, xive->end_base);
356     sysbus_mmio_map(SYS_BUS_DEVICE(xive), 2, xive->tm_base);
357 }
358 
359 static int spapr_xive_get_eas(XiveRouter *xrtr, uint8_t eas_blk,
360                               uint32_t eas_idx, XiveEAS *eas)
361 {
362     SpaprXive *xive = SPAPR_XIVE(xrtr);
363 
364     if (eas_idx >= xive->nr_irqs) {
365         return -1;
366     }
367 
368     *eas = xive->eat[eas_idx];
369     return 0;
370 }
371 
372 static int spapr_xive_get_end(XiveRouter *xrtr,
373                               uint8_t end_blk, uint32_t end_idx, XiveEND *end)
374 {
375     SpaprXive *xive = SPAPR_XIVE(xrtr);
376 
377     if (end_idx >= xive->nr_ends) {
378         return -1;
379     }
380 
381     memcpy(end, &xive->endt[end_idx], sizeof(XiveEND));
382     return 0;
383 }
384 
385 static int spapr_xive_write_end(XiveRouter *xrtr, uint8_t end_blk,
386                                 uint32_t end_idx, XiveEND *end,
387                                 uint8_t word_number)
388 {
389     SpaprXive *xive = SPAPR_XIVE(xrtr);
390 
391     if (end_idx >= xive->nr_ends) {
392         return -1;
393     }
394 
395     memcpy(&xive->endt[end_idx], end, sizeof(XiveEND));
396     return 0;
397 }
398 
399 static int spapr_xive_get_nvt(XiveRouter *xrtr,
400                               uint8_t nvt_blk, uint32_t nvt_idx, XiveNVT *nvt)
401 {
402     uint32_t vcpu_id = spapr_xive_nvt_to_target(nvt_blk, nvt_idx);
403     PowerPCCPU *cpu = spapr_find_cpu(vcpu_id);
404 
405     if (!cpu) {
406         /* TODO: should we assert() if we can find a NVT ? */
407         return -1;
408     }
409 
410     /*
411      * sPAPR does not maintain a NVT table. Return that the NVT is
412      * valid if we have found a matching CPU
413      */
414     nvt->w0 = cpu_to_be32(NVT_W0_VALID);
415     return 0;
416 }
417 
418 static int spapr_xive_write_nvt(XiveRouter *xrtr, uint8_t nvt_blk,
419                                 uint32_t nvt_idx, XiveNVT *nvt,
420                                 uint8_t word_number)
421 {
422     /*
423      * We don't need to write back to the NVTs because the sPAPR
424      * machine should never hit a non-scheduled NVT. It should never
425      * get called.
426      */
427     g_assert_not_reached();
428 }
429 
430 static int spapr_xive_match_nvt(XivePresenter *xptr, uint8_t format,
431                                 uint8_t nvt_blk, uint32_t nvt_idx,
432                                 bool cam_ignore, uint8_t priority,
433                                 uint32_t logic_serv, XiveTCTXMatch *match)
434 {
435     CPUState *cs;
436     int count = 0;
437 
438     CPU_FOREACH(cs) {
439         PowerPCCPU *cpu = POWERPC_CPU(cs);
440         XiveTCTX *tctx = spapr_cpu_state(cpu)->tctx;
441         int ring;
442 
443         /*
444          * Skip partially initialized vCPUs. This can happen when
445          * vCPUs are hotplugged.
446          */
447         if (!tctx) {
448             continue;
449         }
450 
451         /*
452          * Check the thread context CAM lines and record matches.
453          */
454         ring = xive_presenter_tctx_match(xptr, tctx, format, nvt_blk, nvt_idx,
455                                          cam_ignore, logic_serv);
456         /*
457          * Save the matching thread interrupt context and follow on to
458          * check for duplicates which are invalid.
459          */
460         if (ring != -1) {
461             if (match->tctx) {
462                 qemu_log_mask(LOG_GUEST_ERROR, "XIVE: already found a thread "
463                               "context NVT %x/%x\n", nvt_blk, nvt_idx);
464                 return -1;
465             }
466 
467             match->ring = ring;
468             match->tctx = tctx;
469             count++;
470         }
471     }
472 
473     return count;
474 }
475 
476 static uint8_t spapr_xive_get_block_id(XiveRouter *xrtr)
477 {
478     return SPAPR_XIVE_BLOCK_ID;
479 }
480 
481 static const VMStateDescription vmstate_spapr_xive_end = {
482     .name = TYPE_SPAPR_XIVE "/end",
483     .version_id = 1,
484     .minimum_version_id = 1,
485     .fields = (VMStateField []) {
486         VMSTATE_UINT32(w0, XiveEND),
487         VMSTATE_UINT32(w1, XiveEND),
488         VMSTATE_UINT32(w2, XiveEND),
489         VMSTATE_UINT32(w3, XiveEND),
490         VMSTATE_UINT32(w4, XiveEND),
491         VMSTATE_UINT32(w5, XiveEND),
492         VMSTATE_UINT32(w6, XiveEND),
493         VMSTATE_UINT32(w7, XiveEND),
494         VMSTATE_END_OF_LIST()
495     },
496 };
497 
498 static const VMStateDescription vmstate_spapr_xive_eas = {
499     .name = TYPE_SPAPR_XIVE "/eas",
500     .version_id = 1,
501     .minimum_version_id = 1,
502     .fields = (VMStateField []) {
503         VMSTATE_UINT64(w, XiveEAS),
504         VMSTATE_END_OF_LIST()
505     },
506 };
507 
508 static int vmstate_spapr_xive_pre_save(void *opaque)
509 {
510     if (kvm_irqchip_in_kernel()) {
511         return kvmppc_xive_pre_save(SPAPR_XIVE(opaque));
512     }
513 
514     return 0;
515 }
516 
517 /*
518  * Called by the sPAPR IRQ backend 'post_load' method at the machine
519  * level.
520  */
521 static int spapr_xive_post_load(SpaprInterruptController *intc, int version_id)
522 {
523     if (kvm_irqchip_in_kernel()) {
524         return kvmppc_xive_post_load(SPAPR_XIVE(intc), version_id);
525     }
526 
527     return 0;
528 }
529 
530 static const VMStateDescription vmstate_spapr_xive = {
531     .name = TYPE_SPAPR_XIVE,
532     .version_id = 1,
533     .minimum_version_id = 1,
534     .pre_save = vmstate_spapr_xive_pre_save,
535     .post_load = NULL, /* handled at the machine level */
536     .fields = (VMStateField[]) {
537         VMSTATE_UINT32_EQUAL(nr_irqs, SpaprXive, NULL),
538         VMSTATE_STRUCT_VARRAY_POINTER_UINT32(eat, SpaprXive, nr_irqs,
539                                      vmstate_spapr_xive_eas, XiveEAS),
540         VMSTATE_STRUCT_VARRAY_POINTER_UINT32(endt, SpaprXive, nr_ends,
541                                              vmstate_spapr_xive_end, XiveEND),
542         VMSTATE_END_OF_LIST()
543     },
544 };
545 
546 static int spapr_xive_claim_irq(SpaprInterruptController *intc, int lisn,
547                                 bool lsi, Error **errp)
548 {
549     SpaprXive *xive = SPAPR_XIVE(intc);
550     XiveSource *xsrc = &xive->source;
551 
552     assert(lisn < xive->nr_irqs);
553 
554     if (xive_eas_is_valid(&xive->eat[lisn])) {
555         error_setg(errp, "IRQ %d is not free", lisn);
556         return -EBUSY;
557     }
558 
559     /*
560      * Set default values when allocating an IRQ number
561      */
562     xive->eat[lisn].w |= cpu_to_be64(EAS_VALID | EAS_MASKED);
563     if (lsi) {
564         xive_source_irq_set_lsi(xsrc, lisn);
565     }
566 
567     if (kvm_irqchip_in_kernel()) {
568         return kvmppc_xive_source_reset_one(xsrc, lisn, errp);
569     }
570 
571     return 0;
572 }
573 
574 static void spapr_xive_free_irq(SpaprInterruptController *intc, int lisn)
575 {
576     SpaprXive *xive = SPAPR_XIVE(intc);
577     assert(lisn < xive->nr_irqs);
578 
579     xive->eat[lisn].w &= cpu_to_be64(~EAS_VALID);
580 }
581 
582 static Property spapr_xive_properties[] = {
583     DEFINE_PROP_UINT32("nr-irqs", SpaprXive, nr_irqs, 0),
584     DEFINE_PROP_UINT32("nr-ends", SpaprXive, nr_ends, 0),
585     DEFINE_PROP_UINT64("vc-base", SpaprXive, vc_base, SPAPR_XIVE_VC_BASE),
586     DEFINE_PROP_UINT64("tm-base", SpaprXive, tm_base, SPAPR_XIVE_TM_BASE),
587     DEFINE_PROP_END_OF_LIST(),
588 };
589 
590 static int spapr_xive_cpu_intc_create(SpaprInterruptController *intc,
591                                       PowerPCCPU *cpu, Error **errp)
592 {
593     SpaprXive *xive = SPAPR_XIVE(intc);
594     Object *obj;
595     SpaprCpuState *spapr_cpu = spapr_cpu_state(cpu);
596 
597     obj = xive_tctx_create(OBJECT(cpu), XIVE_ROUTER(xive), errp);
598     if (!obj) {
599         return -1;
600     }
601 
602     spapr_cpu->tctx = XIVE_TCTX(obj);
603     return 0;
604 }
605 
606 static void xive_tctx_set_os_cam(XiveTCTX *tctx, uint32_t os_cam)
607 {
608     uint32_t qw1w2 = cpu_to_be32(TM_QW1W2_VO | os_cam);
609     memcpy(&tctx->regs[TM_QW1_OS + TM_WORD2], &qw1w2, 4);
610 }
611 
612 static void spapr_xive_cpu_intc_reset(SpaprInterruptController *intc,
613                                      PowerPCCPU *cpu)
614 {
615     XiveTCTX *tctx = spapr_cpu_state(cpu)->tctx;
616     uint8_t  nvt_blk;
617     uint32_t nvt_idx;
618 
619     xive_tctx_reset(tctx);
620 
621     /*
622      * When a Virtual Processor is scheduled to run on a HW thread,
623      * the hypervisor pushes its identifier in the OS CAM line.
624      * Emulate the same behavior under QEMU.
625      */
626     spapr_xive_cpu_to_nvt(cpu, &nvt_blk, &nvt_idx);
627 
628     xive_tctx_set_os_cam(tctx, xive_nvt_cam_line(nvt_blk, nvt_idx));
629 }
630 
631 static void spapr_xive_cpu_intc_destroy(SpaprInterruptController *intc,
632                                         PowerPCCPU *cpu)
633 {
634     SpaprCpuState *spapr_cpu = spapr_cpu_state(cpu);
635 
636     xive_tctx_destroy(spapr_cpu->tctx);
637     spapr_cpu->tctx = NULL;
638 }
639 
640 static void spapr_xive_set_irq(SpaprInterruptController *intc, int irq, int val)
641 {
642     SpaprXive *xive = SPAPR_XIVE(intc);
643 
644     if (kvm_irqchip_in_kernel()) {
645         kvmppc_xive_source_set_irq(&xive->source, irq, val);
646     } else {
647         xive_source_set_irq(&xive->source, irq, val);
648     }
649 }
650 
651 static void spapr_xive_print_info(SpaprInterruptController *intc, Monitor *mon)
652 {
653     SpaprXive *xive = SPAPR_XIVE(intc);
654     CPUState *cs;
655 
656     CPU_FOREACH(cs) {
657         PowerPCCPU *cpu = POWERPC_CPU(cs);
658 
659         xive_tctx_pic_print_info(spapr_cpu_state(cpu)->tctx, mon);
660     }
661 
662     spapr_xive_pic_print_info(xive, mon);
663 }
664 
665 static void spapr_xive_dt(SpaprInterruptController *intc, uint32_t nr_servers,
666                           void *fdt, uint32_t phandle)
667 {
668     SpaprXive *xive = SPAPR_XIVE(intc);
669     int node;
670     uint64_t timas[2 * 2];
671     /* Interrupt number ranges for the IPIs */
672     uint32_t lisn_ranges[] = {
673         cpu_to_be32(0),
674         cpu_to_be32(nr_servers),
675     };
676     /*
677      * EQ size - the sizes of pages supported by the system 4K, 64K,
678      * 2M, 16M. We only advertise 64K for the moment.
679      */
680     uint32_t eq_sizes[] = {
681         cpu_to_be32(16), /* 64K */
682     };
683     /*
684      * The following array is in sync with the reserved priorities
685      * defined by the 'spapr_xive_priority_is_reserved' routine.
686      */
687     uint32_t plat_res_int_priorities[] = {
688         cpu_to_be32(7),    /* start */
689         cpu_to_be32(0xf8), /* count */
690     };
691 
692     /* Thread Interrupt Management Area : User (ring 3) and OS (ring 2) */
693     timas[0] = cpu_to_be64(xive->tm_base +
694                            XIVE_TM_USER_PAGE * (1ull << TM_SHIFT));
695     timas[1] = cpu_to_be64(1ull << TM_SHIFT);
696     timas[2] = cpu_to_be64(xive->tm_base +
697                            XIVE_TM_OS_PAGE * (1ull << TM_SHIFT));
698     timas[3] = cpu_to_be64(1ull << TM_SHIFT);
699 
700     _FDT(node = fdt_add_subnode(fdt, 0, xive->nodename));
701 
702     _FDT(fdt_setprop_string(fdt, node, "device_type", "power-ivpe"));
703     _FDT(fdt_setprop(fdt, node, "reg", timas, sizeof(timas)));
704 
705     _FDT(fdt_setprop_string(fdt, node, "compatible", "ibm,power-ivpe"));
706     _FDT(fdt_setprop(fdt, node, "ibm,xive-eq-sizes", eq_sizes,
707                      sizeof(eq_sizes)));
708     _FDT(fdt_setprop(fdt, node, "ibm,xive-lisn-ranges", lisn_ranges,
709                      sizeof(lisn_ranges)));
710 
711     /* For Linux to link the LSIs to the interrupt controller. */
712     _FDT(fdt_setprop(fdt, node, "interrupt-controller", NULL, 0));
713     _FDT(fdt_setprop_cell(fdt, node, "#interrupt-cells", 2));
714 
715     /* For SLOF */
716     _FDT(fdt_setprop_cell(fdt, node, "linux,phandle", phandle));
717     _FDT(fdt_setprop_cell(fdt, node, "phandle", phandle));
718 
719     /*
720      * The "ibm,plat-res-int-priorities" property defines the priority
721      * ranges reserved by the hypervisor
722      */
723     _FDT(fdt_setprop(fdt, 0, "ibm,plat-res-int-priorities",
724                      plat_res_int_priorities, sizeof(plat_res_int_priorities)));
725 }
726 
727 static int spapr_xive_activate(SpaprInterruptController *intc,
728                                uint32_t nr_servers, Error **errp)
729 {
730     SpaprXive *xive = SPAPR_XIVE(intc);
731 
732     if (kvm_enabled()) {
733         int rc = spapr_irq_init_kvm(kvmppc_xive_connect, intc, nr_servers,
734                                     errp);
735         if (rc < 0) {
736             return rc;
737         }
738     }
739 
740     /* Activate the XIVE MMIOs */
741     spapr_xive_mmio_set_enabled(xive, true);
742 
743     return 0;
744 }
745 
746 static void spapr_xive_deactivate(SpaprInterruptController *intc)
747 {
748     SpaprXive *xive = SPAPR_XIVE(intc);
749 
750     spapr_xive_mmio_set_enabled(xive, false);
751 
752     if (kvm_irqchip_in_kernel()) {
753         kvmppc_xive_disconnect(intc);
754     }
755 }
756 
757 static void spapr_xive_class_init(ObjectClass *klass, void *data)
758 {
759     DeviceClass *dc = DEVICE_CLASS(klass);
760     XiveRouterClass *xrc = XIVE_ROUTER_CLASS(klass);
761     SpaprInterruptControllerClass *sicc = SPAPR_INTC_CLASS(klass);
762     XivePresenterClass *xpc = XIVE_PRESENTER_CLASS(klass);
763 
764     dc->desc    = "sPAPR XIVE Interrupt Controller";
765     dc->props   = spapr_xive_properties;
766     dc->realize = spapr_xive_realize;
767     dc->vmsd    = &vmstate_spapr_xive;
768 
769     xrc->get_eas = spapr_xive_get_eas;
770     xrc->get_end = spapr_xive_get_end;
771     xrc->write_end = spapr_xive_write_end;
772     xrc->get_nvt = spapr_xive_get_nvt;
773     xrc->write_nvt = spapr_xive_write_nvt;
774     xrc->get_block_id = spapr_xive_get_block_id;
775 
776     sicc->activate = spapr_xive_activate;
777     sicc->deactivate = spapr_xive_deactivate;
778     sicc->cpu_intc_create = spapr_xive_cpu_intc_create;
779     sicc->cpu_intc_reset = spapr_xive_cpu_intc_reset;
780     sicc->cpu_intc_destroy = spapr_xive_cpu_intc_destroy;
781     sicc->claim_irq = spapr_xive_claim_irq;
782     sicc->free_irq = spapr_xive_free_irq;
783     sicc->set_irq = spapr_xive_set_irq;
784     sicc->print_info = spapr_xive_print_info;
785     sicc->dt = spapr_xive_dt;
786     sicc->post_load = spapr_xive_post_load;
787 
788     xpc->match_nvt  = spapr_xive_match_nvt;
789 }
790 
791 static const TypeInfo spapr_xive_info = {
792     .name = TYPE_SPAPR_XIVE,
793     .parent = TYPE_XIVE_ROUTER,
794     .instance_init = spapr_xive_instance_init,
795     .instance_size = sizeof(SpaprXive),
796     .class_init = spapr_xive_class_init,
797     .interfaces = (InterfaceInfo[]) {
798         { TYPE_SPAPR_INTC },
799         { }
800     },
801 };
802 
803 static void spapr_xive_register_types(void)
804 {
805     type_register_static(&spapr_xive_info);
806 }
807 
808 type_init(spapr_xive_register_types)
809 
810 /*
811  * XIVE hcalls
812  *
813  * The terminology used by the XIVE hcalls is the following :
814  *
815  *   TARGET vCPU number
816  *   EQ     Event Queue assigned by OS to receive event data
817  *   ESB    page for source interrupt management
818  *   LISN   Logical Interrupt Source Number identifying a source in the
819  *          machine
820  *   EISN   Effective Interrupt Source Number used by guest OS to
821  *          identify source in the guest
822  *
823  * The EAS, END, NVT structures are not exposed.
824  */
825 
826 /*
827  * Linux hosts under OPAL reserve priority 7 for their own escalation
828  * interrupts (DD2.X POWER9). So we only allow the guest to use
829  * priorities [0..6].
830  */
831 static bool spapr_xive_priority_is_reserved(uint8_t priority)
832 {
833     switch (priority) {
834     case 0 ... 6:
835         return false;
836     case 7: /* OPAL escalation queue */
837     default:
838         return true;
839     }
840 }
841 
842 /*
843  * The H_INT_GET_SOURCE_INFO hcall() is used to obtain the logical
844  * real address of the MMIO page through which the Event State Buffer
845  * entry associated with the value of the "lisn" parameter is managed.
846  *
847  * Parameters:
848  * Input
849  * - R4: "flags"
850  *         Bits 0-63 reserved
851  * - R5: "lisn" is per "interrupts", "interrupt-map", or
852  *       "ibm,xive-lisn-ranges" properties, or as returned by the
853  *       ibm,query-interrupt-source-number RTAS call, or as returned
854  *       by the H_ALLOCATE_VAS_WINDOW hcall
855  *
856  * Output
857  * - R4: "flags"
858  *         Bits 0-59: Reserved
859  *         Bit 60: H_INT_ESB must be used for Event State Buffer
860  *                 management
861  *         Bit 61: 1 == LSI  0 == MSI
862  *         Bit 62: the full function page supports trigger
863  *         Bit 63: Store EOI Supported
864  * - R5: Logical Real address of full function Event State Buffer
865  *       management page, -1 if H_INT_ESB hcall flag is set to 1.
866  * - R6: Logical Real Address of trigger only Event State Buffer
867  *       management page or -1.
868  * - R7: Power of 2 page size for the ESB management pages returned in
869  *       R5 and R6.
870  */
871 
872 #define SPAPR_XIVE_SRC_H_INT_ESB     PPC_BIT(60) /* ESB manage with H_INT_ESB */
873 #define SPAPR_XIVE_SRC_LSI           PPC_BIT(61) /* Virtual LSI type */
874 #define SPAPR_XIVE_SRC_TRIGGER       PPC_BIT(62) /* Trigger and management
875                                                     on same page */
876 #define SPAPR_XIVE_SRC_STORE_EOI     PPC_BIT(63) /* Store EOI support */
877 
878 static target_ulong h_int_get_source_info(PowerPCCPU *cpu,
879                                           SpaprMachineState *spapr,
880                                           target_ulong opcode,
881                                           target_ulong *args)
882 {
883     SpaprXive *xive = spapr->xive;
884     XiveSource *xsrc = &xive->source;
885     target_ulong flags  = args[0];
886     target_ulong lisn   = args[1];
887 
888     if (!spapr_ovec_test(spapr->ov5_cas, OV5_XIVE_EXPLOIT)) {
889         return H_FUNCTION;
890     }
891 
892     if (flags) {
893         return H_PARAMETER;
894     }
895 
896     if (lisn >= xive->nr_irqs) {
897         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: Unknown LISN " TARGET_FMT_lx "\n",
898                       lisn);
899         return H_P2;
900     }
901 
902     if (!xive_eas_is_valid(&xive->eat[lisn])) {
903         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: Invalid LISN " TARGET_FMT_lx "\n",
904                       lisn);
905         return H_P2;
906     }
907 
908     /*
909      * All sources are emulated under the main XIVE object and share
910      * the same characteristics.
911      */
912     args[0] = 0;
913     if (!xive_source_esb_has_2page(xsrc)) {
914         args[0] |= SPAPR_XIVE_SRC_TRIGGER;
915     }
916     if (xsrc->esb_flags & XIVE_SRC_STORE_EOI) {
917         args[0] |= SPAPR_XIVE_SRC_STORE_EOI;
918     }
919 
920     /*
921      * Force the use of the H_INT_ESB hcall in case of an LSI
922      * interrupt. This is necessary under KVM to re-trigger the
923      * interrupt if the level is still asserted
924      */
925     if (xive_source_irq_is_lsi(xsrc, lisn)) {
926         args[0] |= SPAPR_XIVE_SRC_H_INT_ESB | SPAPR_XIVE_SRC_LSI;
927     }
928 
929     if (!(args[0] & SPAPR_XIVE_SRC_H_INT_ESB)) {
930         args[1] = xive->vc_base + xive_source_esb_mgmt(xsrc, lisn);
931     } else {
932         args[1] = -1;
933     }
934 
935     if (xive_source_esb_has_2page(xsrc) &&
936         !(args[0] & SPAPR_XIVE_SRC_H_INT_ESB)) {
937         args[2] = xive->vc_base + xive_source_esb_page(xsrc, lisn);
938     } else {
939         args[2] = -1;
940     }
941 
942     if (xive_source_esb_has_2page(xsrc)) {
943         args[3] = xsrc->esb_shift - 1;
944     } else {
945         args[3] = xsrc->esb_shift;
946     }
947 
948     return H_SUCCESS;
949 }
950 
951 /*
952  * The H_INT_SET_SOURCE_CONFIG hcall() is used to assign a Logical
953  * Interrupt Source to a target. The Logical Interrupt Source is
954  * designated with the "lisn" parameter and the target is designated
955  * with the "target" and "priority" parameters.  Upon return from the
956  * hcall(), no additional interrupts will be directed to the old EQ.
957  *
958  * Parameters:
959  * Input:
960  * - R4: "flags"
961  *         Bits 0-61: Reserved
962  *         Bit 62: set the "eisn" in the EAS
963  *         Bit 63: masks the interrupt source in the hardware interrupt
964  *       control structure. An interrupt masked by this mechanism will
965  *       be dropped, but it's source state bits will still be
966  *       set. There is no race-free way of unmasking and restoring the
967  *       source. Thus this should only be used in interrupts that are
968  *       also masked at the source, and only in cases where the
969  *       interrupt is not meant to be used for a large amount of time
970  *       because no valid target exists for it for example
971  * - R5: "lisn" is per "interrupts", "interrupt-map", or
972  *       "ibm,xive-lisn-ranges" properties, or as returned by the
973  *       ibm,query-interrupt-source-number RTAS call, or as returned by
974  *       the H_ALLOCATE_VAS_WINDOW hcall
975  * - R6: "target" is per "ibm,ppc-interrupt-server#s" or
976  *       "ibm,ppc-interrupt-gserver#s"
977  * - R7: "priority" is a valid priority not in
978  *       "ibm,plat-res-int-priorities"
979  * - R8: "eisn" is the guest EISN associated with the "lisn"
980  *
981  * Output:
982  * - None
983  */
984 
985 #define SPAPR_XIVE_SRC_SET_EISN PPC_BIT(62)
986 #define SPAPR_XIVE_SRC_MASK     PPC_BIT(63)
987 
988 static target_ulong h_int_set_source_config(PowerPCCPU *cpu,
989                                             SpaprMachineState *spapr,
990                                             target_ulong opcode,
991                                             target_ulong *args)
992 {
993     SpaprXive *xive = spapr->xive;
994     XiveEAS eas, new_eas;
995     target_ulong flags    = args[0];
996     target_ulong lisn     = args[1];
997     target_ulong target   = args[2];
998     target_ulong priority = args[3];
999     target_ulong eisn     = args[4];
1000     uint8_t end_blk;
1001     uint32_t end_idx;
1002 
1003     if (!spapr_ovec_test(spapr->ov5_cas, OV5_XIVE_EXPLOIT)) {
1004         return H_FUNCTION;
1005     }
1006 
1007     if (flags & ~(SPAPR_XIVE_SRC_SET_EISN | SPAPR_XIVE_SRC_MASK)) {
1008         return H_PARAMETER;
1009     }
1010 
1011     if (lisn >= xive->nr_irqs) {
1012         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: Unknown LISN " TARGET_FMT_lx "\n",
1013                       lisn);
1014         return H_P2;
1015     }
1016 
1017     eas = xive->eat[lisn];
1018     if (!xive_eas_is_valid(&eas)) {
1019         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: Invalid LISN " TARGET_FMT_lx "\n",
1020                       lisn);
1021         return H_P2;
1022     }
1023 
1024     /* priority 0xff is used to reset the EAS */
1025     if (priority == 0xff) {
1026         new_eas.w = cpu_to_be64(EAS_VALID | EAS_MASKED);
1027         goto out;
1028     }
1029 
1030     if (flags & SPAPR_XIVE_SRC_MASK) {
1031         new_eas.w = eas.w | cpu_to_be64(EAS_MASKED);
1032     } else {
1033         new_eas.w = eas.w & cpu_to_be64(~EAS_MASKED);
1034     }
1035 
1036     if (spapr_xive_priority_is_reserved(priority)) {
1037         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: priority " TARGET_FMT_ld
1038                       " is reserved\n", priority);
1039         return H_P4;
1040     }
1041 
1042     /*
1043      * Validate that "target" is part of the list of threads allocated
1044      * to the partition. For that, find the END corresponding to the
1045      * target.
1046      */
1047     if (spapr_xive_target_to_end(target, priority, &end_blk, &end_idx)) {
1048         return H_P3;
1049     }
1050 
1051     new_eas.w = xive_set_field64(EAS_END_BLOCK, new_eas.w, end_blk);
1052     new_eas.w = xive_set_field64(EAS_END_INDEX, new_eas.w, end_idx);
1053 
1054     if (flags & SPAPR_XIVE_SRC_SET_EISN) {
1055         new_eas.w = xive_set_field64(EAS_END_DATA, new_eas.w, eisn);
1056     }
1057 
1058     if (kvm_irqchip_in_kernel()) {
1059         Error *local_err = NULL;
1060 
1061         kvmppc_xive_set_source_config(xive, lisn, &new_eas, &local_err);
1062         if (local_err) {
1063             error_report_err(local_err);
1064             return H_HARDWARE;
1065         }
1066     }
1067 
1068 out:
1069     xive->eat[lisn] = new_eas;
1070     return H_SUCCESS;
1071 }
1072 
1073 /*
1074  * The H_INT_GET_SOURCE_CONFIG hcall() is used to determine to which
1075  * target/priority pair is assigned to the specified Logical Interrupt
1076  * Source.
1077  *
1078  * Parameters:
1079  * Input:
1080  * - R4: "flags"
1081  *         Bits 0-63 Reserved
1082  * - R5: "lisn" is per "interrupts", "interrupt-map", or
1083  *       "ibm,xive-lisn-ranges" properties, or as returned by the
1084  *       ibm,query-interrupt-source-number RTAS call, or as
1085  *       returned by the H_ALLOCATE_VAS_WINDOW hcall
1086  *
1087  * Output:
1088  * - R4: Target to which the specified Logical Interrupt Source is
1089  *       assigned
1090  * - R5: Priority to which the specified Logical Interrupt Source is
1091  *       assigned
1092  * - R6: EISN for the specified Logical Interrupt Source (this will be
1093  *       equivalent to the LISN if not changed by H_INT_SET_SOURCE_CONFIG)
1094  */
1095 static target_ulong h_int_get_source_config(PowerPCCPU *cpu,
1096                                             SpaprMachineState *spapr,
1097                                             target_ulong opcode,
1098                                             target_ulong *args)
1099 {
1100     SpaprXive *xive = spapr->xive;
1101     target_ulong flags = args[0];
1102     target_ulong lisn = args[1];
1103     XiveEAS eas;
1104     XiveEND *end;
1105     uint8_t nvt_blk;
1106     uint32_t end_idx, nvt_idx;
1107 
1108     if (!spapr_ovec_test(spapr->ov5_cas, OV5_XIVE_EXPLOIT)) {
1109         return H_FUNCTION;
1110     }
1111 
1112     if (flags) {
1113         return H_PARAMETER;
1114     }
1115 
1116     if (lisn >= xive->nr_irqs) {
1117         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: Unknown LISN " TARGET_FMT_lx "\n",
1118                       lisn);
1119         return H_P2;
1120     }
1121 
1122     eas = xive->eat[lisn];
1123     if (!xive_eas_is_valid(&eas)) {
1124         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: Invalid LISN " TARGET_FMT_lx "\n",
1125                       lisn);
1126         return H_P2;
1127     }
1128 
1129     /* EAS_END_BLOCK is unused on sPAPR */
1130     end_idx = xive_get_field64(EAS_END_INDEX, eas.w);
1131 
1132     assert(end_idx < xive->nr_ends);
1133     end = &xive->endt[end_idx];
1134 
1135     nvt_blk = xive_get_field32(END_W6_NVT_BLOCK, end->w6);
1136     nvt_idx = xive_get_field32(END_W6_NVT_INDEX, end->w6);
1137     args[0] = spapr_xive_nvt_to_target(nvt_blk, nvt_idx);
1138 
1139     if (xive_eas_is_masked(&eas)) {
1140         args[1] = 0xff;
1141     } else {
1142         args[1] = xive_get_field32(END_W7_F0_PRIORITY, end->w7);
1143     }
1144 
1145     args[2] = xive_get_field64(EAS_END_DATA, eas.w);
1146 
1147     return H_SUCCESS;
1148 }
1149 
1150 /*
1151  * The H_INT_GET_QUEUE_INFO hcall() is used to get the logical real
1152  * address of the notification management page associated with the
1153  * specified target and priority.
1154  *
1155  * Parameters:
1156  * Input:
1157  * - R4: "flags"
1158  *         Bits 0-63 Reserved
1159  * - R5: "target" is per "ibm,ppc-interrupt-server#s" or
1160  *       "ibm,ppc-interrupt-gserver#s"
1161  * - R6: "priority" is a valid priority not in
1162  *       "ibm,plat-res-int-priorities"
1163  *
1164  * Output:
1165  * - R4: Logical real address of notification page
1166  * - R5: Power of 2 page size of the notification page
1167  */
1168 static target_ulong h_int_get_queue_info(PowerPCCPU *cpu,
1169                                          SpaprMachineState *spapr,
1170                                          target_ulong opcode,
1171                                          target_ulong *args)
1172 {
1173     SpaprXive *xive = spapr->xive;
1174     XiveENDSource *end_xsrc = &xive->end_source;
1175     target_ulong flags = args[0];
1176     target_ulong target = args[1];
1177     target_ulong priority = args[2];
1178     XiveEND *end;
1179     uint8_t end_blk;
1180     uint32_t end_idx;
1181 
1182     if (!spapr_ovec_test(spapr->ov5_cas, OV5_XIVE_EXPLOIT)) {
1183         return H_FUNCTION;
1184     }
1185 
1186     if (flags) {
1187         return H_PARAMETER;
1188     }
1189 
1190     /*
1191      * H_STATE should be returned if a H_INT_RESET is in progress.
1192      * This is not needed when running the emulation under QEMU
1193      */
1194 
1195     if (spapr_xive_priority_is_reserved(priority)) {
1196         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: priority " TARGET_FMT_ld
1197                       " is reserved\n", priority);
1198         return H_P3;
1199     }
1200 
1201     /*
1202      * Validate that "target" is part of the list of threads allocated
1203      * to the partition. For that, find the END corresponding to the
1204      * target.
1205      */
1206     if (spapr_xive_target_to_end(target, priority, &end_blk, &end_idx)) {
1207         return H_P2;
1208     }
1209 
1210     assert(end_idx < xive->nr_ends);
1211     end = &xive->endt[end_idx];
1212 
1213     args[0] = xive->end_base + (1ull << (end_xsrc->esb_shift + 1)) * end_idx;
1214     if (xive_end_is_enqueue(end)) {
1215         args[1] = xive_get_field32(END_W0_QSIZE, end->w0) + 12;
1216     } else {
1217         args[1] = 0;
1218     }
1219 
1220     return H_SUCCESS;
1221 }
1222 
1223 /*
1224  * The H_INT_SET_QUEUE_CONFIG hcall() is used to set or reset a EQ for
1225  * a given "target" and "priority".  It is also used to set the
1226  * notification config associated with the EQ.  An EQ size of 0 is
1227  * used to reset the EQ config for a given target and priority. If
1228  * resetting the EQ config, the END associated with the given "target"
1229  * and "priority" will be changed to disable queueing.
1230  *
1231  * Upon return from the hcall(), no additional interrupts will be
1232  * directed to the old EQ (if one was set). The old EQ (if one was
1233  * set) should be investigated for interrupts that occurred prior to
1234  * or during the hcall().
1235  *
1236  * Parameters:
1237  * Input:
1238  * - R4: "flags"
1239  *         Bits 0-62: Reserved
1240  *         Bit 63: Unconditional Notify (n) per the XIVE spec
1241  * - R5: "target" is per "ibm,ppc-interrupt-server#s" or
1242  *       "ibm,ppc-interrupt-gserver#s"
1243  * - R6: "priority" is a valid priority not in
1244  *       "ibm,plat-res-int-priorities"
1245  * - R7: "eventQueue": The logical real address of the start of the EQ
1246  * - R8: "eventQueueSize": The power of 2 EQ size per "ibm,xive-eq-sizes"
1247  *
1248  * Output:
1249  * - None
1250  */
1251 
1252 #define SPAPR_XIVE_END_ALWAYS_NOTIFY PPC_BIT(63)
1253 
1254 static target_ulong h_int_set_queue_config(PowerPCCPU *cpu,
1255                                            SpaprMachineState *spapr,
1256                                            target_ulong opcode,
1257                                            target_ulong *args)
1258 {
1259     SpaprXive *xive = spapr->xive;
1260     target_ulong flags = args[0];
1261     target_ulong target = args[1];
1262     target_ulong priority = args[2];
1263     target_ulong qpage = args[3];
1264     target_ulong qsize = args[4];
1265     XiveEND end;
1266     uint8_t end_blk, nvt_blk;
1267     uint32_t end_idx, nvt_idx;
1268 
1269     if (!spapr_ovec_test(spapr->ov5_cas, OV5_XIVE_EXPLOIT)) {
1270         return H_FUNCTION;
1271     }
1272 
1273     if (flags & ~SPAPR_XIVE_END_ALWAYS_NOTIFY) {
1274         return H_PARAMETER;
1275     }
1276 
1277     /*
1278      * H_STATE should be returned if a H_INT_RESET is in progress.
1279      * This is not needed when running the emulation under QEMU
1280      */
1281 
1282     if (spapr_xive_priority_is_reserved(priority)) {
1283         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: priority " TARGET_FMT_ld
1284                       " is reserved\n", priority);
1285         return H_P3;
1286     }
1287 
1288     /*
1289      * Validate that "target" is part of the list of threads allocated
1290      * to the partition. For that, find the END corresponding to the
1291      * target.
1292      */
1293 
1294     if (spapr_xive_target_to_end(target, priority, &end_blk, &end_idx)) {
1295         return H_P2;
1296     }
1297 
1298     assert(end_idx < xive->nr_ends);
1299     memcpy(&end, &xive->endt[end_idx], sizeof(XiveEND));
1300 
1301     switch (qsize) {
1302     case 12:
1303     case 16:
1304     case 21:
1305     case 24:
1306         if (!QEMU_IS_ALIGNED(qpage, 1ul << qsize)) {
1307             qemu_log_mask(LOG_GUEST_ERROR, "XIVE: EQ @0x%" HWADDR_PRIx
1308                           " is not naturally aligned with %" HWADDR_PRIx "\n",
1309                           qpage, (hwaddr)1 << qsize);
1310             return H_P4;
1311         }
1312         end.w2 = cpu_to_be32((qpage >> 32) & 0x0fffffff);
1313         end.w3 = cpu_to_be32(qpage & 0xffffffff);
1314         end.w0 |= cpu_to_be32(END_W0_ENQUEUE);
1315         end.w0 = xive_set_field32(END_W0_QSIZE, end.w0, qsize - 12);
1316         break;
1317     case 0:
1318         /* reset queue and disable queueing */
1319         spapr_xive_end_reset(&end);
1320         goto out;
1321 
1322     default:
1323         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: invalid EQ size %"PRIx64"\n",
1324                       qsize);
1325         return H_P5;
1326     }
1327 
1328     if (qsize) {
1329         hwaddr plen = 1 << qsize;
1330         void *eq;
1331 
1332         /*
1333          * Validate the guest EQ. We should also check that the queue
1334          * has been zeroed by the OS.
1335          */
1336         eq = address_space_map(CPU(cpu)->as, qpage, &plen, true,
1337                                MEMTXATTRS_UNSPECIFIED);
1338         if (plen != 1 << qsize) {
1339             qemu_log_mask(LOG_GUEST_ERROR, "XIVE: failed to map EQ @0x%"
1340                           HWADDR_PRIx "\n", qpage);
1341             return H_P4;
1342         }
1343         address_space_unmap(CPU(cpu)->as, eq, plen, true, plen);
1344     }
1345 
1346     /* "target" should have been validated above */
1347     if (spapr_xive_target_to_nvt(target, &nvt_blk, &nvt_idx)) {
1348         g_assert_not_reached();
1349     }
1350 
1351     /*
1352      * Ensure the priority and target are correctly set (they will not
1353      * be right after allocation)
1354      */
1355     end.w6 = xive_set_field32(END_W6_NVT_BLOCK, 0ul, nvt_blk) |
1356         xive_set_field32(END_W6_NVT_INDEX, 0ul, nvt_idx);
1357     end.w7 = xive_set_field32(END_W7_F0_PRIORITY, 0ul, priority);
1358 
1359     if (flags & SPAPR_XIVE_END_ALWAYS_NOTIFY) {
1360         end.w0 |= cpu_to_be32(END_W0_UCOND_NOTIFY);
1361     } else {
1362         end.w0 &= cpu_to_be32((uint32_t)~END_W0_UCOND_NOTIFY);
1363     }
1364 
1365     /*
1366      * The generation bit for the END starts at 1 and The END page
1367      * offset counter starts at 0.
1368      */
1369     end.w1 = cpu_to_be32(END_W1_GENERATION) |
1370         xive_set_field32(END_W1_PAGE_OFF, 0ul, 0ul);
1371     end.w0 |= cpu_to_be32(END_W0_VALID);
1372 
1373     /*
1374      * TODO: issue syncs required to ensure all in-flight interrupts
1375      * are complete on the old END
1376      */
1377 
1378 out:
1379     if (kvm_irqchip_in_kernel()) {
1380         Error *local_err = NULL;
1381 
1382         kvmppc_xive_set_queue_config(xive, end_blk, end_idx, &end, &local_err);
1383         if (local_err) {
1384             error_report_err(local_err);
1385             return H_HARDWARE;
1386         }
1387     }
1388 
1389     /* Update END */
1390     memcpy(&xive->endt[end_idx], &end, sizeof(XiveEND));
1391     return H_SUCCESS;
1392 }
1393 
1394 /*
1395  * The H_INT_GET_QUEUE_CONFIG hcall() is used to get a EQ for a given
1396  * target and priority.
1397  *
1398  * Parameters:
1399  * Input:
1400  * - R4: "flags"
1401  *         Bits 0-62: Reserved
1402  *         Bit 63: Debug: Return debug data
1403  * - R5: "target" is per "ibm,ppc-interrupt-server#s" or
1404  *       "ibm,ppc-interrupt-gserver#s"
1405  * - R6: "priority" is a valid priority not in
1406  *       "ibm,plat-res-int-priorities"
1407  *
1408  * Output:
1409  * - R4: "flags":
1410  *       Bits 0-61: Reserved
1411  *       Bit 62: The value of Event Queue Generation Number (g) per
1412  *              the XIVE spec if "Debug" = 1
1413  *       Bit 63: The value of Unconditional Notify (n) per the XIVE spec
1414  * - R5: The logical real address of the start of the EQ
1415  * - R6: The power of 2 EQ size per "ibm,xive-eq-sizes"
1416  * - R7: The value of Event Queue Offset Counter per XIVE spec
1417  *       if "Debug" = 1, else 0
1418  *
1419  */
1420 
1421 #define SPAPR_XIVE_END_DEBUG     PPC_BIT(63)
1422 
1423 static target_ulong h_int_get_queue_config(PowerPCCPU *cpu,
1424                                            SpaprMachineState *spapr,
1425                                            target_ulong opcode,
1426                                            target_ulong *args)
1427 {
1428     SpaprXive *xive = spapr->xive;
1429     target_ulong flags = args[0];
1430     target_ulong target = args[1];
1431     target_ulong priority = args[2];
1432     XiveEND *end;
1433     uint8_t end_blk;
1434     uint32_t end_idx;
1435 
1436     if (!spapr_ovec_test(spapr->ov5_cas, OV5_XIVE_EXPLOIT)) {
1437         return H_FUNCTION;
1438     }
1439 
1440     if (flags & ~SPAPR_XIVE_END_DEBUG) {
1441         return H_PARAMETER;
1442     }
1443 
1444     /*
1445      * H_STATE should be returned if a H_INT_RESET is in progress.
1446      * This is not needed when running the emulation under QEMU
1447      */
1448 
1449     if (spapr_xive_priority_is_reserved(priority)) {
1450         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: priority " TARGET_FMT_ld
1451                       " is reserved\n", priority);
1452         return H_P3;
1453     }
1454 
1455     /*
1456      * Validate that "target" is part of the list of threads allocated
1457      * to the partition. For that, find the END corresponding to the
1458      * target.
1459      */
1460     if (spapr_xive_target_to_end(target, priority, &end_blk, &end_idx)) {
1461         return H_P2;
1462     }
1463 
1464     assert(end_idx < xive->nr_ends);
1465     end = &xive->endt[end_idx];
1466 
1467     args[0] = 0;
1468     if (xive_end_is_notify(end)) {
1469         args[0] |= SPAPR_XIVE_END_ALWAYS_NOTIFY;
1470     }
1471 
1472     if (xive_end_is_enqueue(end)) {
1473         args[1] = xive_end_qaddr(end);
1474         args[2] = xive_get_field32(END_W0_QSIZE, end->w0) + 12;
1475     } else {
1476         args[1] = 0;
1477         args[2] = 0;
1478     }
1479 
1480     if (kvm_irqchip_in_kernel()) {
1481         Error *local_err = NULL;
1482 
1483         kvmppc_xive_get_queue_config(xive, end_blk, end_idx, end, &local_err);
1484         if (local_err) {
1485             error_report_err(local_err);
1486             return H_HARDWARE;
1487         }
1488     }
1489 
1490     /* TODO: do we need any locking on the END ? */
1491     if (flags & SPAPR_XIVE_END_DEBUG) {
1492         /* Load the event queue generation number into the return flags */
1493         args[0] |= (uint64_t)xive_get_field32(END_W1_GENERATION, end->w1) << 62;
1494 
1495         /* Load R7 with the event queue offset counter */
1496         args[3] = xive_get_field32(END_W1_PAGE_OFF, end->w1);
1497     } else {
1498         args[3] = 0;
1499     }
1500 
1501     return H_SUCCESS;
1502 }
1503 
1504 /*
1505  * The H_INT_SET_OS_REPORTING_LINE hcall() is used to set the
1506  * reporting cache line pair for the calling thread.  The reporting
1507  * cache lines will contain the OS interrupt context when the OS
1508  * issues a CI store byte to @TIMA+0xC10 to acknowledge the OS
1509  * interrupt. The reporting cache lines can be reset by inputting -1
1510  * in "reportingLine".  Issuing the CI store byte without reporting
1511  * cache lines registered will result in the data not being accessible
1512  * to the OS.
1513  *
1514  * Parameters:
1515  * Input:
1516  * - R4: "flags"
1517  *         Bits 0-63: Reserved
1518  * - R5: "reportingLine": The logical real address of the reporting cache
1519  *       line pair
1520  *
1521  * Output:
1522  * - None
1523  */
1524 static target_ulong h_int_set_os_reporting_line(PowerPCCPU *cpu,
1525                                                 SpaprMachineState *spapr,
1526                                                 target_ulong opcode,
1527                                                 target_ulong *args)
1528 {
1529     if (!spapr_ovec_test(spapr->ov5_cas, OV5_XIVE_EXPLOIT)) {
1530         return H_FUNCTION;
1531     }
1532 
1533     /*
1534      * H_STATE should be returned if a H_INT_RESET is in progress.
1535      * This is not needed when running the emulation under QEMU
1536      */
1537 
1538     /* TODO: H_INT_SET_OS_REPORTING_LINE */
1539     return H_FUNCTION;
1540 }
1541 
1542 /*
1543  * The H_INT_GET_OS_REPORTING_LINE hcall() is used to get the logical
1544  * real address of the reporting cache line pair set for the input
1545  * "target".  If no reporting cache line pair has been set, -1 is
1546  * returned.
1547  *
1548  * Parameters:
1549  * Input:
1550  * - R4: "flags"
1551  *         Bits 0-63: Reserved
1552  * - R5: "target" is per "ibm,ppc-interrupt-server#s" or
1553  *       "ibm,ppc-interrupt-gserver#s"
1554  * - R6: "reportingLine": The logical real address of the reporting
1555  *        cache line pair
1556  *
1557  * Output:
1558  * - R4: The logical real address of the reporting line if set, else -1
1559  */
1560 static target_ulong h_int_get_os_reporting_line(PowerPCCPU *cpu,
1561                                                 SpaprMachineState *spapr,
1562                                                 target_ulong opcode,
1563                                                 target_ulong *args)
1564 {
1565     if (!spapr_ovec_test(spapr->ov5_cas, OV5_XIVE_EXPLOIT)) {
1566         return H_FUNCTION;
1567     }
1568 
1569     /*
1570      * H_STATE should be returned if a H_INT_RESET is in progress.
1571      * This is not needed when running the emulation under QEMU
1572      */
1573 
1574     /* TODO: H_INT_GET_OS_REPORTING_LINE */
1575     return H_FUNCTION;
1576 }
1577 
1578 /*
1579  * The H_INT_ESB hcall() is used to issue a load or store to the ESB
1580  * page for the input "lisn".  This hcall is only supported for LISNs
1581  * that have the ESB hcall flag set to 1 when returned from hcall()
1582  * H_INT_GET_SOURCE_INFO.
1583  *
1584  * Parameters:
1585  * Input:
1586  * - R4: "flags"
1587  *         Bits 0-62: Reserved
1588  *         bit 63: Store: Store=1, store operation, else load operation
1589  * - R5: "lisn" is per "interrupts", "interrupt-map", or
1590  *       "ibm,xive-lisn-ranges" properties, or as returned by the
1591  *       ibm,query-interrupt-source-number RTAS call, or as
1592  *       returned by the H_ALLOCATE_VAS_WINDOW hcall
1593  * - R6: "esbOffset" is the offset into the ESB page for the load or
1594  *       store operation
1595  * - R7: "storeData" is the data to write for a store operation
1596  *
1597  * Output:
1598  * - R4: The value of the load if load operation, else -1
1599  */
1600 
1601 #define SPAPR_XIVE_ESB_STORE PPC_BIT(63)
1602 
1603 static target_ulong h_int_esb(PowerPCCPU *cpu,
1604                               SpaprMachineState *spapr,
1605                               target_ulong opcode,
1606                               target_ulong *args)
1607 {
1608     SpaprXive *xive = spapr->xive;
1609     XiveEAS eas;
1610     target_ulong flags  = args[0];
1611     target_ulong lisn   = args[1];
1612     target_ulong offset = args[2];
1613     target_ulong data   = args[3];
1614     hwaddr mmio_addr;
1615     XiveSource *xsrc = &xive->source;
1616 
1617     if (!spapr_ovec_test(spapr->ov5_cas, OV5_XIVE_EXPLOIT)) {
1618         return H_FUNCTION;
1619     }
1620 
1621     if (flags & ~SPAPR_XIVE_ESB_STORE) {
1622         return H_PARAMETER;
1623     }
1624 
1625     if (lisn >= xive->nr_irqs) {
1626         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: Unknown LISN " TARGET_FMT_lx "\n",
1627                       lisn);
1628         return H_P2;
1629     }
1630 
1631     eas = xive->eat[lisn];
1632     if (!xive_eas_is_valid(&eas)) {
1633         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: Invalid LISN " TARGET_FMT_lx "\n",
1634                       lisn);
1635         return H_P2;
1636     }
1637 
1638     if (offset > (1ull << xsrc->esb_shift)) {
1639         return H_P3;
1640     }
1641 
1642     if (kvm_irqchip_in_kernel()) {
1643         args[0] = kvmppc_xive_esb_rw(xsrc, lisn, offset, data,
1644                                      flags & SPAPR_XIVE_ESB_STORE);
1645     } else {
1646         mmio_addr = xive->vc_base + xive_source_esb_mgmt(xsrc, lisn) + offset;
1647 
1648         if (dma_memory_rw(&address_space_memory, mmio_addr, &data, 8,
1649                           (flags & SPAPR_XIVE_ESB_STORE))) {
1650             qemu_log_mask(LOG_GUEST_ERROR, "XIVE: failed to access ESB @0x%"
1651                           HWADDR_PRIx "\n", mmio_addr);
1652             return H_HARDWARE;
1653         }
1654         args[0] = (flags & SPAPR_XIVE_ESB_STORE) ? -1 : data;
1655     }
1656     return H_SUCCESS;
1657 }
1658 
1659 /*
1660  * The H_INT_SYNC hcall() is used to issue hardware syncs that will
1661  * ensure any in flight events for the input lisn are in the event
1662  * queue.
1663  *
1664  * Parameters:
1665  * Input:
1666  * - R4: "flags"
1667  *         Bits 0-63: Reserved
1668  * - R5: "lisn" is per "interrupts", "interrupt-map", or
1669  *       "ibm,xive-lisn-ranges" properties, or as returned by the
1670  *       ibm,query-interrupt-source-number RTAS call, or as
1671  *       returned by the H_ALLOCATE_VAS_WINDOW hcall
1672  *
1673  * Output:
1674  * - None
1675  */
1676 static target_ulong h_int_sync(PowerPCCPU *cpu,
1677                                SpaprMachineState *spapr,
1678                                target_ulong opcode,
1679                                target_ulong *args)
1680 {
1681     SpaprXive *xive = spapr->xive;
1682     XiveEAS eas;
1683     target_ulong flags = args[0];
1684     target_ulong lisn = args[1];
1685 
1686     if (!spapr_ovec_test(spapr->ov5_cas, OV5_XIVE_EXPLOIT)) {
1687         return H_FUNCTION;
1688     }
1689 
1690     if (flags) {
1691         return H_PARAMETER;
1692     }
1693 
1694     if (lisn >= xive->nr_irqs) {
1695         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: Unknown LISN " TARGET_FMT_lx "\n",
1696                       lisn);
1697         return H_P2;
1698     }
1699 
1700     eas = xive->eat[lisn];
1701     if (!xive_eas_is_valid(&eas)) {
1702         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: Invalid LISN " TARGET_FMT_lx "\n",
1703                       lisn);
1704         return H_P2;
1705     }
1706 
1707     /*
1708      * H_STATE should be returned if a H_INT_RESET is in progress.
1709      * This is not needed when running the emulation under QEMU
1710      */
1711 
1712     /*
1713      * This is not real hardware. Nothing to be done unless when
1714      * under KVM
1715      */
1716 
1717     if (kvm_irqchip_in_kernel()) {
1718         Error *local_err = NULL;
1719 
1720         kvmppc_xive_sync_source(xive, lisn, &local_err);
1721         if (local_err) {
1722             error_report_err(local_err);
1723             return H_HARDWARE;
1724         }
1725     }
1726     return H_SUCCESS;
1727 }
1728 
1729 /*
1730  * The H_INT_RESET hcall() is used to reset all of the partition's
1731  * interrupt exploitation structures to their initial state.  This
1732  * means losing all previously set interrupt state set via
1733  * H_INT_SET_SOURCE_CONFIG and H_INT_SET_QUEUE_CONFIG.
1734  *
1735  * Parameters:
1736  * Input:
1737  * - R4: "flags"
1738  *         Bits 0-63: Reserved
1739  *
1740  * Output:
1741  * - None
1742  */
1743 static target_ulong h_int_reset(PowerPCCPU *cpu,
1744                                 SpaprMachineState *spapr,
1745                                 target_ulong opcode,
1746                                 target_ulong *args)
1747 {
1748     SpaprXive *xive = spapr->xive;
1749     target_ulong flags   = args[0];
1750 
1751     if (!spapr_ovec_test(spapr->ov5_cas, OV5_XIVE_EXPLOIT)) {
1752         return H_FUNCTION;
1753     }
1754 
1755     if (flags) {
1756         return H_PARAMETER;
1757     }
1758 
1759     device_reset(DEVICE(xive));
1760 
1761     if (kvm_irqchip_in_kernel()) {
1762         Error *local_err = NULL;
1763 
1764         kvmppc_xive_reset(xive, &local_err);
1765         if (local_err) {
1766             error_report_err(local_err);
1767             return H_HARDWARE;
1768         }
1769     }
1770     return H_SUCCESS;
1771 }
1772 
1773 void spapr_xive_hcall_init(SpaprMachineState *spapr)
1774 {
1775     spapr_register_hypercall(H_INT_GET_SOURCE_INFO, h_int_get_source_info);
1776     spapr_register_hypercall(H_INT_SET_SOURCE_CONFIG, h_int_set_source_config);
1777     spapr_register_hypercall(H_INT_GET_SOURCE_CONFIG, h_int_get_source_config);
1778     spapr_register_hypercall(H_INT_GET_QUEUE_INFO, h_int_get_queue_info);
1779     spapr_register_hypercall(H_INT_SET_QUEUE_CONFIG, h_int_set_queue_config);
1780     spapr_register_hypercall(H_INT_GET_QUEUE_CONFIG, h_int_get_queue_config);
1781     spapr_register_hypercall(H_INT_SET_OS_REPORTING_LINE,
1782                              h_int_set_os_reporting_line);
1783     spapr_register_hypercall(H_INT_GET_OS_REPORTING_LINE,
1784                              h_int_get_os_reporting_line);
1785     spapr_register_hypercall(H_INT_ESB, h_int_esb);
1786     spapr_register_hypercall(H_INT_SYNC, h_int_sync);
1787     spapr_register_hypercall(H_INT_RESET, h_int_reset);
1788 }
1789