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