xref: /openbmc/qemu/hw/intc/xive.c (revision 7bfc759c02b8d19fd76d70d138deea0025f6f461)
1 /*
2  * QEMU PowerPC 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 "qapi/error.h"
13 #include "target/ppc/cpu.h"
14 #include "sysemu/cpus.h"
15 #include "sysemu/dma.h"
16 #include "hw/qdev-properties.h"
17 #include "monitor/monitor.h"
18 #include "hw/ppc/xive.h"
19 #include "hw/ppc/xive_regs.h"
20 
21 /*
22  * XIVE Thread Interrupt Management context
23  */
24 
25 /*
26  * Convert a priority number to an Interrupt Pending Buffer (IPB)
27  * register, which indicates a pending interrupt at the priority
28  * corresponding to the bit number
29  */
30 static uint8_t priority_to_ipb(uint8_t priority)
31 {
32     return priority > XIVE_PRIORITY_MAX ?
33         0 : 1 << (XIVE_PRIORITY_MAX - priority);
34 }
35 
36 /*
37  * Convert an Interrupt Pending Buffer (IPB) register to a Pending
38  * Interrupt Priority Register (PIPR), which contains the priority of
39  * the most favored pending notification.
40  */
41 static uint8_t ipb_to_pipr(uint8_t ibp)
42 {
43     return ibp ? clz32((uint32_t)ibp << 24) : 0xff;
44 }
45 
46 static void ipb_update(uint8_t *regs, uint8_t priority)
47 {
48     regs[TM_IPB] |= priority_to_ipb(priority);
49     regs[TM_PIPR] = ipb_to_pipr(regs[TM_IPB]);
50 }
51 
52 static uint8_t exception_mask(uint8_t ring)
53 {
54     switch (ring) {
55     case TM_QW1_OS:
56         return TM_QW1_NSR_EO;
57     case TM_QW3_HV_PHYS:
58         return TM_QW3_NSR_HE;
59     default:
60         g_assert_not_reached();
61     }
62 }
63 
64 static uint64_t xive_tctx_accept(XiveTCTX *tctx, uint8_t ring)
65 {
66     uint8_t *regs = &tctx->regs[ring];
67     uint8_t nsr = regs[TM_NSR];
68     uint8_t mask = exception_mask(ring);
69 
70     qemu_irq_lower(tctx->output);
71 
72     if (regs[TM_NSR] & mask) {
73         uint8_t cppr = regs[TM_PIPR];
74 
75         regs[TM_CPPR] = cppr;
76 
77         /* Reset the pending buffer bit */
78         regs[TM_IPB] &= ~priority_to_ipb(cppr);
79         regs[TM_PIPR] = ipb_to_pipr(regs[TM_IPB]);
80 
81         /* Drop Exception bit */
82         regs[TM_NSR] &= ~mask;
83     }
84 
85     return (nsr << 8) | regs[TM_CPPR];
86 }
87 
88 static void xive_tctx_notify(XiveTCTX *tctx, uint8_t ring)
89 {
90     uint8_t *regs = &tctx->regs[ring];
91 
92     if (regs[TM_PIPR] < regs[TM_CPPR]) {
93         switch (ring) {
94         case TM_QW1_OS:
95             regs[TM_NSR] |= TM_QW1_NSR_EO;
96             break;
97         case TM_QW3_HV_PHYS:
98             regs[TM_NSR] |= (TM_QW3_NSR_HE_PHYS << 6);
99             break;
100         default:
101             g_assert_not_reached();
102         }
103         qemu_irq_raise(tctx->output);
104     }
105 }
106 
107 static void xive_tctx_set_cppr(XiveTCTX *tctx, uint8_t ring, uint8_t cppr)
108 {
109     if (cppr > XIVE_PRIORITY_MAX) {
110         cppr = 0xff;
111     }
112 
113     tctx->regs[ring + TM_CPPR] = cppr;
114 
115     /* CPPR has changed, check if we need to raise a pending exception */
116     xive_tctx_notify(tctx, ring);
117 }
118 
119 /*
120  * XIVE Thread Interrupt Management Area (TIMA)
121  */
122 
123 static void xive_tm_set_hv_cppr(XiveTCTX *tctx, hwaddr offset,
124                                 uint64_t value, unsigned size)
125 {
126     xive_tctx_set_cppr(tctx, TM_QW3_HV_PHYS, value & 0xff);
127 }
128 
129 static uint64_t xive_tm_ack_hv_reg(XiveTCTX *tctx, hwaddr offset, unsigned size)
130 {
131     return xive_tctx_accept(tctx, TM_QW3_HV_PHYS);
132 }
133 
134 static uint64_t xive_tm_pull_pool_ctx(XiveTCTX *tctx, hwaddr offset,
135                                       unsigned size)
136 {
137     uint64_t ret;
138 
139     ret = tctx->regs[TM_QW2_HV_POOL + TM_WORD2] & TM_QW2W2_POOL_CAM;
140     tctx->regs[TM_QW2_HV_POOL + TM_WORD2] &= ~TM_QW2W2_POOL_CAM;
141     return ret;
142 }
143 
144 static void xive_tm_vt_push(XiveTCTX *tctx, hwaddr offset,
145                             uint64_t value, unsigned size)
146 {
147     tctx->regs[TM_QW3_HV_PHYS + TM_WORD2] = value & 0xff;
148 }
149 
150 static uint64_t xive_tm_vt_poll(XiveTCTX *tctx, hwaddr offset, unsigned size)
151 {
152     return tctx->regs[TM_QW3_HV_PHYS + TM_WORD2] & 0xff;
153 }
154 
155 /*
156  * Define an access map for each page of the TIMA that we will use in
157  * the memory region ops to filter values when doing loads and stores
158  * of raw registers values
159  *
160  * Registers accessibility bits :
161  *
162  *    0x0 - no access
163  *    0x1 - write only
164  *    0x2 - read only
165  *    0x3 - read/write
166  */
167 
168 static const uint8_t xive_tm_hw_view[] = {
169     /* QW-0 User */   3, 0, 0, 0,   0, 0, 0, 0,   3, 3, 3, 3,   0, 0, 0, 0,
170     /* QW-1 OS   */   3, 3, 3, 3,   3, 3, 0, 3,   3, 3, 3, 3,   0, 0, 0, 0,
171     /* QW-2 POOL */   0, 0, 3, 3,   0, 0, 0, 0,   3, 3, 3, 3,   0, 0, 0, 0,
172     /* QW-3 PHYS */   3, 3, 3, 3,   0, 3, 0, 3,   3, 0, 0, 3,   3, 3, 3, 0,
173 };
174 
175 static const uint8_t xive_tm_hv_view[] = {
176     /* QW-0 User */   3, 0, 0, 0,   0, 0, 0, 0,   3, 3, 3, 3,   0, 0, 0, 0,
177     /* QW-1 OS   */   3, 3, 3, 3,   3, 3, 0, 3,   3, 3, 3, 3,   0, 0, 0, 0,
178     /* QW-2 POOL */   0, 0, 3, 3,   0, 0, 0, 0,   0, 3, 3, 3,   0, 0, 0, 0,
179     /* QW-3 PHYS */   3, 3, 3, 3,   0, 3, 0, 3,   3, 0, 0, 3,   0, 0, 0, 0,
180 };
181 
182 static const uint8_t xive_tm_os_view[] = {
183     /* QW-0 User */   3, 0, 0, 0,   0, 0, 0, 0,   3, 3, 3, 3,   0, 0, 0, 0,
184     /* QW-1 OS   */   2, 3, 2, 2,   2, 2, 0, 2,   0, 0, 0, 0,   0, 0, 0, 0,
185     /* QW-2 POOL */   0, 0, 0, 0,   0, 0, 0, 0,   0, 0, 0, 0,   0, 0, 0, 0,
186     /* QW-3 PHYS */   0, 0, 0, 0,   0, 0, 0, 0,   0, 0, 0, 0,   0, 0, 0, 0,
187 };
188 
189 static const uint8_t xive_tm_user_view[] = {
190     /* QW-0 User */   3, 0, 0, 0,   0, 0, 0, 0,   0, 0, 0, 0,   0, 0, 0, 0,
191     /* QW-1 OS   */   0, 0, 0, 0,   0, 0, 0, 0,   0, 0, 0, 0,   0, 0, 0, 0,
192     /* QW-2 POOL */   0, 0, 0, 0,   0, 0, 0, 0,   0, 0, 0, 0,   0, 0, 0, 0,
193     /* QW-3 PHYS */   0, 0, 0, 0,   0, 0, 0, 0,   0, 0, 0, 0,   0, 0, 0, 0,
194 };
195 
196 /*
197  * Overall TIMA access map for the thread interrupt management context
198  * registers
199  */
200 static const uint8_t *xive_tm_views[] = {
201     [XIVE_TM_HW_PAGE]   = xive_tm_hw_view,
202     [XIVE_TM_HV_PAGE]   = xive_tm_hv_view,
203     [XIVE_TM_OS_PAGE]   = xive_tm_os_view,
204     [XIVE_TM_USER_PAGE] = xive_tm_user_view,
205 };
206 
207 /*
208  * Computes a register access mask for a given offset in the TIMA
209  */
210 static uint64_t xive_tm_mask(hwaddr offset, unsigned size, bool write)
211 {
212     uint8_t page_offset = (offset >> TM_SHIFT) & 0x3;
213     uint8_t reg_offset = offset & 0x3F;
214     uint8_t reg_mask = write ? 0x1 : 0x2;
215     uint64_t mask = 0x0;
216     int i;
217 
218     for (i = 0; i < size; i++) {
219         if (xive_tm_views[page_offset][reg_offset + i] & reg_mask) {
220             mask |= (uint64_t) 0xff << (8 * (size - i - 1));
221         }
222     }
223 
224     return mask;
225 }
226 
227 static void xive_tm_raw_write(XiveTCTX *tctx, hwaddr offset, uint64_t value,
228                               unsigned size)
229 {
230     uint8_t ring_offset = offset & 0x30;
231     uint8_t reg_offset = offset & 0x3F;
232     uint64_t mask = xive_tm_mask(offset, size, true);
233     int i;
234 
235     /*
236      * Only 4 or 8 bytes stores are allowed and the User ring is
237      * excluded
238      */
239     if (size < 4 || !mask || ring_offset == TM_QW0_USER) {
240         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: invalid write access at TIMA @%"
241                       HWADDR_PRIx"\n", offset);
242         return;
243     }
244 
245     /*
246      * Use the register offset for the raw values and filter out
247      * reserved values
248      */
249     for (i = 0; i < size; i++) {
250         uint8_t byte_mask = (mask >> (8 * (size - i - 1)));
251         if (byte_mask) {
252             tctx->regs[reg_offset + i] = (value >> (8 * (size - i - 1))) &
253                 byte_mask;
254         }
255     }
256 }
257 
258 static uint64_t xive_tm_raw_read(XiveTCTX *tctx, hwaddr offset, unsigned size)
259 {
260     uint8_t ring_offset = offset & 0x30;
261     uint8_t reg_offset = offset & 0x3F;
262     uint64_t mask = xive_tm_mask(offset, size, false);
263     uint64_t ret;
264     int i;
265 
266     /*
267      * Only 4 or 8 bytes loads are allowed and the User ring is
268      * excluded
269      */
270     if (size < 4 || !mask || ring_offset == TM_QW0_USER) {
271         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: invalid read access at TIMA @%"
272                       HWADDR_PRIx"\n", offset);
273         return -1;
274     }
275 
276     /* Use the register offset for the raw values */
277     ret = 0;
278     for (i = 0; i < size; i++) {
279         ret |= (uint64_t) tctx->regs[reg_offset + i] << (8 * (size - i - 1));
280     }
281 
282     /* filter out reserved values */
283     return ret & mask;
284 }
285 
286 /*
287  * The TM context is mapped twice within each page. Stores and loads
288  * to the first mapping below 2K write and read the specified values
289  * without modification. The second mapping above 2K performs specific
290  * state changes (side effects) in addition to setting/returning the
291  * interrupt management area context of the processor thread.
292  */
293 static uint64_t xive_tm_ack_os_reg(XiveTCTX *tctx, hwaddr offset, unsigned size)
294 {
295     return xive_tctx_accept(tctx, TM_QW1_OS);
296 }
297 
298 static void xive_tm_set_os_cppr(XiveTCTX *tctx, hwaddr offset,
299                                 uint64_t value, unsigned size)
300 {
301     xive_tctx_set_cppr(tctx, TM_QW1_OS, value & 0xff);
302 }
303 
304 /*
305  * Adjust the IPB to allow a CPU to process event queues of other
306  * priorities during one physical interrupt cycle.
307  */
308 static void xive_tm_set_os_pending(XiveTCTX *tctx, hwaddr offset,
309                                    uint64_t value, unsigned size)
310 {
311     ipb_update(&tctx->regs[TM_QW1_OS], value & 0xff);
312     xive_tctx_notify(tctx, TM_QW1_OS);
313 }
314 
315 /*
316  * Define a mapping of "special" operations depending on the TIMA page
317  * offset and the size of the operation.
318  */
319 typedef struct XiveTmOp {
320     uint8_t  page_offset;
321     uint32_t op_offset;
322     unsigned size;
323     void     (*write_handler)(XiveTCTX *tctx, hwaddr offset, uint64_t value,
324                               unsigned size);
325     uint64_t (*read_handler)(XiveTCTX *tctx, hwaddr offset, unsigned size);
326 } XiveTmOp;
327 
328 static const XiveTmOp xive_tm_operations[] = {
329     /*
330      * MMIOs below 2K : raw values and special operations without side
331      * effects
332      */
333     { XIVE_TM_OS_PAGE, TM_QW1_OS + TM_CPPR,   1, xive_tm_set_os_cppr, NULL },
334     { XIVE_TM_HV_PAGE, TM_QW3_HV_PHYS + TM_CPPR, 1, xive_tm_set_hv_cppr, NULL },
335     { XIVE_TM_HV_PAGE, TM_QW3_HV_PHYS + TM_WORD2, 1, xive_tm_vt_push, NULL },
336     { XIVE_TM_HV_PAGE, TM_QW3_HV_PHYS + TM_WORD2, 1, NULL, xive_tm_vt_poll },
337 
338     /* MMIOs above 2K : special operations with side effects */
339     { XIVE_TM_OS_PAGE, TM_SPC_ACK_OS_REG,     2, NULL, xive_tm_ack_os_reg },
340     { XIVE_TM_OS_PAGE, TM_SPC_SET_OS_PENDING, 1, xive_tm_set_os_pending, NULL },
341     { XIVE_TM_HV_PAGE, TM_SPC_ACK_HV_REG,     2, NULL, xive_tm_ack_hv_reg },
342     { XIVE_TM_HV_PAGE, TM_SPC_PULL_POOL_CTX,  4, NULL, xive_tm_pull_pool_ctx },
343     { XIVE_TM_HV_PAGE, TM_SPC_PULL_POOL_CTX,  8, NULL, xive_tm_pull_pool_ctx },
344 };
345 
346 static const XiveTmOp *xive_tm_find_op(hwaddr offset, unsigned size, bool write)
347 {
348     uint8_t page_offset = (offset >> TM_SHIFT) & 0x3;
349     uint32_t op_offset = offset & 0xFFF;
350     int i;
351 
352     for (i = 0; i < ARRAY_SIZE(xive_tm_operations); i++) {
353         const XiveTmOp *xto = &xive_tm_operations[i];
354 
355         /* Accesses done from a more privileged TIMA page is allowed */
356         if (xto->page_offset >= page_offset &&
357             xto->op_offset == op_offset &&
358             xto->size == size &&
359             ((write && xto->write_handler) || (!write && xto->read_handler))) {
360             return xto;
361         }
362     }
363     return NULL;
364 }
365 
366 /*
367  * TIMA MMIO handlers
368  */
369 void xive_tctx_tm_write(XiveTCTX *tctx, hwaddr offset, uint64_t value,
370                         unsigned size)
371 {
372     const XiveTmOp *xto;
373 
374     /*
375      * TODO: check V bit in Q[0-3]W2
376      */
377 
378     /*
379      * First, check for special operations in the 2K region
380      */
381     if (offset & 0x800) {
382         xto = xive_tm_find_op(offset, size, true);
383         if (!xto) {
384             qemu_log_mask(LOG_GUEST_ERROR, "XIVE: invalid write access at TIMA"
385                           "@%"HWADDR_PRIx"\n", offset);
386         } else {
387             xto->write_handler(tctx, offset, value, size);
388         }
389         return;
390     }
391 
392     /*
393      * Then, for special operations in the region below 2K.
394      */
395     xto = xive_tm_find_op(offset, size, true);
396     if (xto) {
397         xto->write_handler(tctx, offset, value, size);
398         return;
399     }
400 
401     /*
402      * Finish with raw access to the register values
403      */
404     xive_tm_raw_write(tctx, offset, value, size);
405 }
406 
407 uint64_t xive_tctx_tm_read(XiveTCTX *tctx, hwaddr offset, unsigned size)
408 {
409     const XiveTmOp *xto;
410 
411     /*
412      * TODO: check V bit in Q[0-3]W2
413      */
414 
415     /*
416      * First, check for special operations in the 2K region
417      */
418     if (offset & 0x800) {
419         xto = xive_tm_find_op(offset, size, false);
420         if (!xto) {
421             qemu_log_mask(LOG_GUEST_ERROR, "XIVE: invalid read access to TIMA"
422                           "@%"HWADDR_PRIx"\n", offset);
423             return -1;
424         }
425         return xto->read_handler(tctx, offset, size);
426     }
427 
428     /*
429      * Then, for special operations in the region below 2K.
430      */
431     xto = xive_tm_find_op(offset, size, false);
432     if (xto) {
433         return xto->read_handler(tctx, offset, size);
434     }
435 
436     /*
437      * Finish with raw access to the register values
438      */
439     return xive_tm_raw_read(tctx, offset, size);
440 }
441 
442 static void xive_tm_write(void *opaque, hwaddr offset,
443                           uint64_t value, unsigned size)
444 {
445     XiveTCTX *tctx = xive_router_get_tctx(XIVE_ROUTER(opaque), current_cpu);
446 
447     xive_tctx_tm_write(tctx, offset, value, size);
448 }
449 
450 static uint64_t xive_tm_read(void *opaque, hwaddr offset, unsigned size)
451 {
452     XiveTCTX *tctx = xive_router_get_tctx(XIVE_ROUTER(opaque), current_cpu);
453 
454     return xive_tctx_tm_read(tctx, offset, size);
455 }
456 
457 const MemoryRegionOps xive_tm_ops = {
458     .read = xive_tm_read,
459     .write = xive_tm_write,
460     .endianness = DEVICE_BIG_ENDIAN,
461     .valid = {
462         .min_access_size = 1,
463         .max_access_size = 8,
464     },
465     .impl = {
466         .min_access_size = 1,
467         .max_access_size = 8,
468     },
469 };
470 
471 static inline uint32_t xive_tctx_word2(uint8_t *ring)
472 {
473     return *((uint32_t *) &ring[TM_WORD2]);
474 }
475 
476 static char *xive_tctx_ring_print(uint8_t *ring)
477 {
478     uint32_t w2 = xive_tctx_word2(ring);
479 
480     return g_strdup_printf("%02x   %02x  %02x    %02x   %02x  "
481                    "%02x  %02x   %02x  %08x",
482                    ring[TM_NSR], ring[TM_CPPR], ring[TM_IPB], ring[TM_LSMFB],
483                    ring[TM_ACK_CNT], ring[TM_INC], ring[TM_AGE], ring[TM_PIPR],
484                    be32_to_cpu(w2));
485 }
486 
487 static const char * const xive_tctx_ring_names[] = {
488     "USER", "OS", "POOL", "PHYS",
489 };
490 
491 void xive_tctx_pic_print_info(XiveTCTX *tctx, Monitor *mon)
492 {
493     int cpu_index = tctx->cs ? tctx->cs->cpu_index : -1;
494     int i;
495 
496     if (kvm_irqchip_in_kernel()) {
497         Error *local_err = NULL;
498 
499         kvmppc_xive_cpu_synchronize_state(tctx, &local_err);
500         if (local_err) {
501             error_report_err(local_err);
502             return;
503         }
504     }
505 
506     monitor_printf(mon, "CPU[%04x]:   QW   NSR CPPR IPB LSMFB ACK# INC AGE PIPR"
507                    "  W2\n", cpu_index);
508 
509     for (i = 0; i < XIVE_TM_RING_COUNT; i++) {
510         char *s = xive_tctx_ring_print(&tctx->regs[i * XIVE_TM_RING_SIZE]);
511         monitor_printf(mon, "CPU[%04x]: %4s    %s\n", cpu_index,
512                        xive_tctx_ring_names[i], s);
513         g_free(s);
514     }
515 }
516 
517 static void xive_tctx_reset(void *dev)
518 {
519     XiveTCTX *tctx = XIVE_TCTX(dev);
520 
521     memset(tctx->regs, 0, sizeof(tctx->regs));
522 
523     /* Set some defaults */
524     tctx->regs[TM_QW1_OS + TM_LSMFB] = 0xFF;
525     tctx->regs[TM_QW1_OS + TM_ACK_CNT] = 0xFF;
526     tctx->regs[TM_QW1_OS + TM_AGE] = 0xFF;
527 
528     /*
529      * Initialize PIPR to 0xFF to avoid phantom interrupts when the
530      * CPPR is first set.
531      */
532     tctx->regs[TM_QW1_OS + TM_PIPR] =
533         ipb_to_pipr(tctx->regs[TM_QW1_OS + TM_IPB]);
534     tctx->regs[TM_QW3_HV_PHYS + TM_PIPR] =
535         ipb_to_pipr(tctx->regs[TM_QW3_HV_PHYS + TM_IPB]);
536 }
537 
538 static void xive_tctx_realize(DeviceState *dev, Error **errp)
539 {
540     XiveTCTX *tctx = XIVE_TCTX(dev);
541     PowerPCCPU *cpu;
542     CPUPPCState *env;
543     Object *obj;
544     Error *local_err = NULL;
545 
546     obj = object_property_get_link(OBJECT(dev), "cpu", &local_err);
547     if (!obj) {
548         error_propagate(errp, local_err);
549         error_prepend(errp, "required link 'cpu' not found: ");
550         return;
551     }
552 
553     cpu = POWERPC_CPU(obj);
554     tctx->cs = CPU(obj);
555 
556     env = &cpu->env;
557     switch (PPC_INPUT(env)) {
558     case PPC_FLAGS_INPUT_POWER9:
559         tctx->output = env->irq_inputs[POWER9_INPUT_INT];
560         break;
561 
562     default:
563         error_setg(errp, "XIVE interrupt controller does not support "
564                    "this CPU bus model");
565         return;
566     }
567 
568     /* Connect the presenter to the VCPU (required for CPU hotplug) */
569     if (kvm_irqchip_in_kernel()) {
570         kvmppc_xive_cpu_connect(tctx, &local_err);
571         if (local_err) {
572             error_propagate(errp, local_err);
573             return;
574         }
575     }
576 
577     qemu_register_reset(xive_tctx_reset, dev);
578 }
579 
580 static void xive_tctx_unrealize(DeviceState *dev, Error **errp)
581 {
582     qemu_unregister_reset(xive_tctx_reset, dev);
583 }
584 
585 static const VMStateDescription vmstate_xive_tctx = {
586     .name = TYPE_XIVE_TCTX,
587     .version_id = 1,
588     .minimum_version_id = 1,
589     .fields = (VMStateField[]) {
590         VMSTATE_BUFFER(regs, XiveTCTX),
591         VMSTATE_END_OF_LIST()
592     },
593 };
594 
595 static void xive_tctx_class_init(ObjectClass *klass, void *data)
596 {
597     DeviceClass *dc = DEVICE_CLASS(klass);
598 
599     dc->desc = "XIVE Interrupt Thread Context";
600     dc->realize = xive_tctx_realize;
601     dc->unrealize = xive_tctx_unrealize;
602     dc->vmsd = &vmstate_xive_tctx;
603 }
604 
605 static const TypeInfo xive_tctx_info = {
606     .name          = TYPE_XIVE_TCTX,
607     .parent        = TYPE_DEVICE,
608     .instance_size = sizeof(XiveTCTX),
609     .class_init    = xive_tctx_class_init,
610 };
611 
612 Object *xive_tctx_create(Object *cpu, XiveRouter *xrtr, Error **errp)
613 {
614     Error *local_err = NULL;
615     Object *obj;
616 
617     obj = object_new(TYPE_XIVE_TCTX);
618     object_property_add_child(cpu, TYPE_XIVE_TCTX, obj, &error_abort);
619     object_unref(obj);
620     object_property_add_const_link(obj, "cpu", cpu, &error_abort);
621     object_property_set_bool(obj, true, "realized", &local_err);
622     if (local_err) {
623         goto error;
624     }
625 
626     return obj;
627 
628 error:
629     object_unparent(obj);
630     error_propagate(errp, local_err);
631     return NULL;
632 }
633 
634 /*
635  * XIVE ESB helpers
636  */
637 
638 static uint8_t xive_esb_set(uint8_t *pq, uint8_t value)
639 {
640     uint8_t old_pq = *pq & 0x3;
641 
642     *pq &= ~0x3;
643     *pq |= value & 0x3;
644 
645     return old_pq;
646 }
647 
648 static bool xive_esb_trigger(uint8_t *pq)
649 {
650     uint8_t old_pq = *pq & 0x3;
651 
652     switch (old_pq) {
653     case XIVE_ESB_RESET:
654         xive_esb_set(pq, XIVE_ESB_PENDING);
655         return true;
656     case XIVE_ESB_PENDING:
657     case XIVE_ESB_QUEUED:
658         xive_esb_set(pq, XIVE_ESB_QUEUED);
659         return false;
660     case XIVE_ESB_OFF:
661         xive_esb_set(pq, XIVE_ESB_OFF);
662         return false;
663     default:
664          g_assert_not_reached();
665     }
666 }
667 
668 static bool xive_esb_eoi(uint8_t *pq)
669 {
670     uint8_t old_pq = *pq & 0x3;
671 
672     switch (old_pq) {
673     case XIVE_ESB_RESET:
674     case XIVE_ESB_PENDING:
675         xive_esb_set(pq, XIVE_ESB_RESET);
676         return false;
677     case XIVE_ESB_QUEUED:
678         xive_esb_set(pq, XIVE_ESB_PENDING);
679         return true;
680     case XIVE_ESB_OFF:
681         xive_esb_set(pq, XIVE_ESB_OFF);
682         return false;
683     default:
684          g_assert_not_reached();
685     }
686 }
687 
688 /*
689  * XIVE Interrupt Source (or IVSE)
690  */
691 
692 uint8_t xive_source_esb_get(XiveSource *xsrc, uint32_t srcno)
693 {
694     assert(srcno < xsrc->nr_irqs);
695 
696     return xsrc->status[srcno] & 0x3;
697 }
698 
699 uint8_t xive_source_esb_set(XiveSource *xsrc, uint32_t srcno, uint8_t pq)
700 {
701     assert(srcno < xsrc->nr_irqs);
702 
703     return xive_esb_set(&xsrc->status[srcno], pq);
704 }
705 
706 /*
707  * Returns whether the event notification should be forwarded.
708  */
709 static bool xive_source_lsi_trigger(XiveSource *xsrc, uint32_t srcno)
710 {
711     uint8_t old_pq = xive_source_esb_get(xsrc, srcno);
712 
713     xsrc->status[srcno] |= XIVE_STATUS_ASSERTED;
714 
715     switch (old_pq) {
716     case XIVE_ESB_RESET:
717         xive_source_esb_set(xsrc, srcno, XIVE_ESB_PENDING);
718         return true;
719     default:
720         return false;
721     }
722 }
723 
724 /*
725  * Returns whether the event notification should be forwarded.
726  */
727 static bool xive_source_esb_trigger(XiveSource *xsrc, uint32_t srcno)
728 {
729     bool ret;
730 
731     assert(srcno < xsrc->nr_irqs);
732 
733     ret = xive_esb_trigger(&xsrc->status[srcno]);
734 
735     if (xive_source_irq_is_lsi(xsrc, srcno) &&
736         xive_source_esb_get(xsrc, srcno) == XIVE_ESB_QUEUED) {
737         qemu_log_mask(LOG_GUEST_ERROR,
738                       "XIVE: queued an event on LSI IRQ %d\n", srcno);
739     }
740 
741     return ret;
742 }
743 
744 /*
745  * Returns whether the event notification should be forwarded.
746  */
747 static bool xive_source_esb_eoi(XiveSource *xsrc, uint32_t srcno)
748 {
749     bool ret;
750 
751     assert(srcno < xsrc->nr_irqs);
752 
753     ret = xive_esb_eoi(&xsrc->status[srcno]);
754 
755     /*
756      * LSI sources do not set the Q bit but they can still be
757      * asserted, in which case we should forward a new event
758      * notification
759      */
760     if (xive_source_irq_is_lsi(xsrc, srcno) &&
761         xsrc->status[srcno] & XIVE_STATUS_ASSERTED) {
762         ret = xive_source_lsi_trigger(xsrc, srcno);
763     }
764 
765     return ret;
766 }
767 
768 /*
769  * Forward the source event notification to the Router
770  */
771 static void xive_source_notify(XiveSource *xsrc, int srcno)
772 {
773     XiveNotifierClass *xnc = XIVE_NOTIFIER_GET_CLASS(xsrc->xive);
774 
775     if (xnc->notify) {
776         xnc->notify(xsrc->xive, srcno);
777     }
778 }
779 
780 /*
781  * In a two pages ESB MMIO setting, even page is the trigger page, odd
782  * page is for management
783  */
784 static inline bool addr_is_even(hwaddr addr, uint32_t shift)
785 {
786     return !((addr >> shift) & 1);
787 }
788 
789 static inline bool xive_source_is_trigger_page(XiveSource *xsrc, hwaddr addr)
790 {
791     return xive_source_esb_has_2page(xsrc) &&
792         addr_is_even(addr, xsrc->esb_shift - 1);
793 }
794 
795 /*
796  * ESB MMIO loads
797  *                      Trigger page    Management/EOI page
798  *
799  * ESB MMIO setting     2 pages         1 or 2 pages
800  *
801  * 0x000 .. 0x3FF       -1              EOI and return 0|1
802  * 0x400 .. 0x7FF       -1              EOI and return 0|1
803  * 0x800 .. 0xBFF       -1              return PQ
804  * 0xC00 .. 0xCFF       -1              return PQ and atomically PQ=00
805  * 0xD00 .. 0xDFF       -1              return PQ and atomically PQ=01
806  * 0xE00 .. 0xDFF       -1              return PQ and atomically PQ=10
807  * 0xF00 .. 0xDFF       -1              return PQ and atomically PQ=11
808  */
809 static uint64_t xive_source_esb_read(void *opaque, hwaddr addr, unsigned size)
810 {
811     XiveSource *xsrc = XIVE_SOURCE(opaque);
812     uint32_t offset = addr & 0xFFF;
813     uint32_t srcno = addr >> xsrc->esb_shift;
814     uint64_t ret = -1;
815 
816     /* In a two pages ESB MMIO setting, trigger page should not be read */
817     if (xive_source_is_trigger_page(xsrc, addr)) {
818         qemu_log_mask(LOG_GUEST_ERROR,
819                       "XIVE: invalid load on IRQ %d trigger page at "
820                       "0x%"HWADDR_PRIx"\n", srcno, addr);
821         return -1;
822     }
823 
824     switch (offset) {
825     case XIVE_ESB_LOAD_EOI ... XIVE_ESB_LOAD_EOI + 0x7FF:
826         ret = xive_source_esb_eoi(xsrc, srcno);
827 
828         /* Forward the source event notification for routing */
829         if (ret) {
830             xive_source_notify(xsrc, srcno);
831         }
832         break;
833 
834     case XIVE_ESB_GET ... XIVE_ESB_GET + 0x3FF:
835         ret = xive_source_esb_get(xsrc, srcno);
836         break;
837 
838     case XIVE_ESB_SET_PQ_00 ... XIVE_ESB_SET_PQ_00 + 0x0FF:
839     case XIVE_ESB_SET_PQ_01 ... XIVE_ESB_SET_PQ_01 + 0x0FF:
840     case XIVE_ESB_SET_PQ_10 ... XIVE_ESB_SET_PQ_10 + 0x0FF:
841     case XIVE_ESB_SET_PQ_11 ... XIVE_ESB_SET_PQ_11 + 0x0FF:
842         ret = xive_source_esb_set(xsrc, srcno, (offset >> 8) & 0x3);
843         break;
844     default:
845         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: invalid ESB load addr %x\n",
846                       offset);
847     }
848 
849     return ret;
850 }
851 
852 /*
853  * ESB MMIO stores
854  *                      Trigger page    Management/EOI page
855  *
856  * ESB MMIO setting     2 pages         1 or 2 pages
857  *
858  * 0x000 .. 0x3FF       Trigger         Trigger
859  * 0x400 .. 0x7FF       Trigger         EOI
860  * 0x800 .. 0xBFF       Trigger         undefined
861  * 0xC00 .. 0xCFF       Trigger         PQ=00
862  * 0xD00 .. 0xDFF       Trigger         PQ=01
863  * 0xE00 .. 0xDFF       Trigger         PQ=10
864  * 0xF00 .. 0xDFF       Trigger         PQ=11
865  */
866 static void xive_source_esb_write(void *opaque, hwaddr addr,
867                                   uint64_t value, unsigned size)
868 {
869     XiveSource *xsrc = XIVE_SOURCE(opaque);
870     uint32_t offset = addr & 0xFFF;
871     uint32_t srcno = addr >> xsrc->esb_shift;
872     bool notify = false;
873 
874     /* In a two pages ESB MMIO setting, trigger page only triggers */
875     if (xive_source_is_trigger_page(xsrc, addr)) {
876         notify = xive_source_esb_trigger(xsrc, srcno);
877         goto out;
878     }
879 
880     switch (offset) {
881     case 0 ... 0x3FF:
882         notify = xive_source_esb_trigger(xsrc, srcno);
883         break;
884 
885     case XIVE_ESB_STORE_EOI ... XIVE_ESB_STORE_EOI + 0x3FF:
886         if (!(xsrc->esb_flags & XIVE_SRC_STORE_EOI)) {
887             qemu_log_mask(LOG_GUEST_ERROR,
888                           "XIVE: invalid Store EOI for IRQ %d\n", srcno);
889             return;
890         }
891 
892         notify = xive_source_esb_eoi(xsrc, srcno);
893         break;
894 
895     case XIVE_ESB_SET_PQ_00 ... XIVE_ESB_SET_PQ_00 + 0x0FF:
896     case XIVE_ESB_SET_PQ_01 ... XIVE_ESB_SET_PQ_01 + 0x0FF:
897     case XIVE_ESB_SET_PQ_10 ... XIVE_ESB_SET_PQ_10 + 0x0FF:
898     case XIVE_ESB_SET_PQ_11 ... XIVE_ESB_SET_PQ_11 + 0x0FF:
899         xive_source_esb_set(xsrc, srcno, (offset >> 8) & 0x3);
900         break;
901 
902     default:
903         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: invalid ESB write addr %x\n",
904                       offset);
905         return;
906     }
907 
908 out:
909     /* Forward the source event notification for routing */
910     if (notify) {
911         xive_source_notify(xsrc, srcno);
912     }
913 }
914 
915 static const MemoryRegionOps xive_source_esb_ops = {
916     .read = xive_source_esb_read,
917     .write = xive_source_esb_write,
918     .endianness = DEVICE_BIG_ENDIAN,
919     .valid = {
920         .min_access_size = 8,
921         .max_access_size = 8,
922     },
923     .impl = {
924         .min_access_size = 8,
925         .max_access_size = 8,
926     },
927 };
928 
929 void xive_source_set_irq(void *opaque, int srcno, int val)
930 {
931     XiveSource *xsrc = XIVE_SOURCE(opaque);
932     bool notify = false;
933 
934     if (xive_source_irq_is_lsi(xsrc, srcno)) {
935         if (val) {
936             notify = xive_source_lsi_trigger(xsrc, srcno);
937         } else {
938             xsrc->status[srcno] &= ~XIVE_STATUS_ASSERTED;
939         }
940     } else {
941         if (val) {
942             notify = xive_source_esb_trigger(xsrc, srcno);
943         }
944     }
945 
946     /* Forward the source event notification for routing */
947     if (notify) {
948         xive_source_notify(xsrc, srcno);
949     }
950 }
951 
952 void xive_source_pic_print_info(XiveSource *xsrc, uint32_t offset, Monitor *mon)
953 {
954     int i;
955 
956     for (i = 0; i < xsrc->nr_irqs; i++) {
957         uint8_t pq = xive_source_esb_get(xsrc, i);
958 
959         if (pq == XIVE_ESB_OFF) {
960             continue;
961         }
962 
963         monitor_printf(mon, "  %08x %s %c%c%c\n", i + offset,
964                        xive_source_irq_is_lsi(xsrc, i) ? "LSI" : "MSI",
965                        pq & XIVE_ESB_VAL_P ? 'P' : '-',
966                        pq & XIVE_ESB_VAL_Q ? 'Q' : '-',
967                        xsrc->status[i] & XIVE_STATUS_ASSERTED ? 'A' : ' ');
968     }
969 }
970 
971 static void xive_source_reset(void *dev)
972 {
973     XiveSource *xsrc = XIVE_SOURCE(dev);
974 
975     /* Do not clear the LSI bitmap */
976 
977     /* PQs are initialized to 0b01 (Q=1) which corresponds to "ints off" */
978     memset(xsrc->status, XIVE_ESB_OFF, xsrc->nr_irqs);
979 
980     if (kvm_irqchip_in_kernel()) {
981         kvmppc_xive_source_reset(xsrc, &error_fatal);
982     }
983 }
984 
985 static void xive_source_realize(DeviceState *dev, Error **errp)
986 {
987     XiveSource *xsrc = XIVE_SOURCE(dev);
988     Object *obj;
989     Error *local_err = NULL;
990 
991     obj = object_property_get_link(OBJECT(dev), "xive", &local_err);
992     if (!obj) {
993         error_propagate(errp, local_err);
994         error_prepend(errp, "required link 'xive' not found: ");
995         return;
996     }
997 
998     xsrc->xive = XIVE_NOTIFIER(obj);
999 
1000     if (!xsrc->nr_irqs) {
1001         error_setg(errp, "Number of interrupt needs to be greater than 0");
1002         return;
1003     }
1004 
1005     if (xsrc->esb_shift != XIVE_ESB_4K &&
1006         xsrc->esb_shift != XIVE_ESB_4K_2PAGE &&
1007         xsrc->esb_shift != XIVE_ESB_64K &&
1008         xsrc->esb_shift != XIVE_ESB_64K_2PAGE) {
1009         error_setg(errp, "Invalid ESB shift setting");
1010         return;
1011     }
1012 
1013     xsrc->status = g_malloc0(xsrc->nr_irqs);
1014     xsrc->lsi_map = bitmap_new(xsrc->nr_irqs);
1015 
1016     if (!kvm_irqchip_in_kernel()) {
1017         memory_region_init_io(&xsrc->esb_mmio, OBJECT(xsrc),
1018                               &xive_source_esb_ops, xsrc, "xive.esb",
1019                               (1ull << xsrc->esb_shift) * xsrc->nr_irqs);
1020     }
1021 
1022     qemu_register_reset(xive_source_reset, dev);
1023 }
1024 
1025 static const VMStateDescription vmstate_xive_source = {
1026     .name = TYPE_XIVE_SOURCE,
1027     .version_id = 1,
1028     .minimum_version_id = 1,
1029     .fields = (VMStateField[]) {
1030         VMSTATE_UINT32_EQUAL(nr_irqs, XiveSource, NULL),
1031         VMSTATE_VBUFFER_UINT32(status, XiveSource, 1, NULL, nr_irqs),
1032         VMSTATE_END_OF_LIST()
1033     },
1034 };
1035 
1036 /*
1037  * The default XIVE interrupt source setting for the ESB MMIOs is two
1038  * 64k pages without Store EOI, to be in sync with KVM.
1039  */
1040 static Property xive_source_properties[] = {
1041     DEFINE_PROP_UINT64("flags", XiveSource, esb_flags, 0),
1042     DEFINE_PROP_UINT32("nr-irqs", XiveSource, nr_irqs, 0),
1043     DEFINE_PROP_UINT32("shift", XiveSource, esb_shift, XIVE_ESB_64K_2PAGE),
1044     DEFINE_PROP_END_OF_LIST(),
1045 };
1046 
1047 static void xive_source_class_init(ObjectClass *klass, void *data)
1048 {
1049     DeviceClass *dc = DEVICE_CLASS(klass);
1050 
1051     dc->desc    = "XIVE Interrupt Source";
1052     dc->props   = xive_source_properties;
1053     dc->realize = xive_source_realize;
1054     dc->vmsd    = &vmstate_xive_source;
1055 }
1056 
1057 static const TypeInfo xive_source_info = {
1058     .name          = TYPE_XIVE_SOURCE,
1059     .parent        = TYPE_DEVICE,
1060     .instance_size = sizeof(XiveSource),
1061     .class_init    = xive_source_class_init,
1062 };
1063 
1064 /*
1065  * XiveEND helpers
1066  */
1067 
1068 void xive_end_queue_pic_print_info(XiveEND *end, uint32_t width, Monitor *mon)
1069 {
1070     uint64_t qaddr_base = xive_end_qaddr(end);
1071     uint32_t qsize = xive_get_field32(END_W0_QSIZE, end->w0);
1072     uint32_t qindex = xive_get_field32(END_W1_PAGE_OFF, end->w1);
1073     uint32_t qentries = 1 << (qsize + 10);
1074     int i;
1075 
1076     /*
1077      * print out the [ (qindex - (width - 1)) .. (qindex + 1)] window
1078      */
1079     monitor_printf(mon, " [ ");
1080     qindex = (qindex - (width - 1)) & (qentries - 1);
1081     for (i = 0; i < width; i++) {
1082         uint64_t qaddr = qaddr_base + (qindex << 2);
1083         uint32_t qdata = -1;
1084 
1085         if (dma_memory_read(&address_space_memory, qaddr, &qdata,
1086                             sizeof(qdata))) {
1087             qemu_log_mask(LOG_GUEST_ERROR, "XIVE: failed to read EQ @0x%"
1088                           HWADDR_PRIx "\n", qaddr);
1089             return;
1090         }
1091         monitor_printf(mon, "%s%08x ", i == width - 1 ? "^" : "",
1092                        be32_to_cpu(qdata));
1093         qindex = (qindex + 1) & (qentries - 1);
1094     }
1095 }
1096 
1097 void xive_end_pic_print_info(XiveEND *end, uint32_t end_idx, Monitor *mon)
1098 {
1099     uint64_t qaddr_base = xive_end_qaddr(end);
1100     uint32_t qindex = xive_get_field32(END_W1_PAGE_OFF, end->w1);
1101     uint32_t qgen = xive_get_field32(END_W1_GENERATION, end->w1);
1102     uint32_t qsize = xive_get_field32(END_W0_QSIZE, end->w0);
1103     uint32_t qentries = 1 << (qsize + 10);
1104 
1105     uint32_t nvt = xive_get_field32(END_W6_NVT_INDEX, end->w6);
1106     uint8_t priority = xive_get_field32(END_W7_F0_PRIORITY, end->w7);
1107 
1108     if (!xive_end_is_valid(end)) {
1109         return;
1110     }
1111 
1112     monitor_printf(mon, "  %08x %c%c%c%c%c prio:%d nvt:%04x eq:@%08"PRIx64
1113                    "% 6d/%5d ^%d", end_idx,
1114                    xive_end_is_valid(end)    ? 'v' : '-',
1115                    xive_end_is_enqueue(end)  ? 'q' : '-',
1116                    xive_end_is_notify(end)   ? 'n' : '-',
1117                    xive_end_is_backlog(end)  ? 'b' : '-',
1118                    xive_end_is_escalate(end) ? 'e' : '-',
1119                    priority, nvt, qaddr_base, qindex, qentries, qgen);
1120 
1121     xive_end_queue_pic_print_info(end, 6, mon);
1122     monitor_printf(mon, "]\n");
1123 }
1124 
1125 static void xive_end_enqueue(XiveEND *end, uint32_t data)
1126 {
1127     uint64_t qaddr_base = xive_end_qaddr(end);
1128     uint32_t qsize = xive_get_field32(END_W0_QSIZE, end->w0);
1129     uint32_t qindex = xive_get_field32(END_W1_PAGE_OFF, end->w1);
1130     uint32_t qgen = xive_get_field32(END_W1_GENERATION, end->w1);
1131 
1132     uint64_t qaddr = qaddr_base + (qindex << 2);
1133     uint32_t qdata = cpu_to_be32((qgen << 31) | (data & 0x7fffffff));
1134     uint32_t qentries = 1 << (qsize + 10);
1135 
1136     if (dma_memory_write(&address_space_memory, qaddr, &qdata, sizeof(qdata))) {
1137         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: failed to write END data @0x%"
1138                       HWADDR_PRIx "\n", qaddr);
1139         return;
1140     }
1141 
1142     qindex = (qindex + 1) & (qentries - 1);
1143     if (qindex == 0) {
1144         qgen ^= 1;
1145         end->w1 = xive_set_field32(END_W1_GENERATION, end->w1, qgen);
1146     }
1147     end->w1 = xive_set_field32(END_W1_PAGE_OFF, end->w1, qindex);
1148 }
1149 
1150 /*
1151  * XIVE Router (aka. Virtualization Controller or IVRE)
1152  */
1153 
1154 int xive_router_get_eas(XiveRouter *xrtr, uint8_t eas_blk, uint32_t eas_idx,
1155                         XiveEAS *eas)
1156 {
1157     XiveRouterClass *xrc = XIVE_ROUTER_GET_CLASS(xrtr);
1158 
1159     return xrc->get_eas(xrtr, eas_blk, eas_idx, eas);
1160 }
1161 
1162 int xive_router_get_end(XiveRouter *xrtr, uint8_t end_blk, uint32_t end_idx,
1163                         XiveEND *end)
1164 {
1165    XiveRouterClass *xrc = XIVE_ROUTER_GET_CLASS(xrtr);
1166 
1167    return xrc->get_end(xrtr, end_blk, end_idx, end);
1168 }
1169 
1170 int xive_router_write_end(XiveRouter *xrtr, uint8_t end_blk, uint32_t end_idx,
1171                           XiveEND *end, uint8_t word_number)
1172 {
1173    XiveRouterClass *xrc = XIVE_ROUTER_GET_CLASS(xrtr);
1174 
1175    return xrc->write_end(xrtr, end_blk, end_idx, end, word_number);
1176 }
1177 
1178 int xive_router_get_nvt(XiveRouter *xrtr, uint8_t nvt_blk, uint32_t nvt_idx,
1179                         XiveNVT *nvt)
1180 {
1181    XiveRouterClass *xrc = XIVE_ROUTER_GET_CLASS(xrtr);
1182 
1183    return xrc->get_nvt(xrtr, nvt_blk, nvt_idx, nvt);
1184 }
1185 
1186 int xive_router_write_nvt(XiveRouter *xrtr, uint8_t nvt_blk, uint32_t nvt_idx,
1187                         XiveNVT *nvt, uint8_t word_number)
1188 {
1189    XiveRouterClass *xrc = XIVE_ROUTER_GET_CLASS(xrtr);
1190 
1191    return xrc->write_nvt(xrtr, nvt_blk, nvt_idx, nvt, word_number);
1192 }
1193 
1194 XiveTCTX *xive_router_get_tctx(XiveRouter *xrtr, CPUState *cs)
1195 {
1196     XiveRouterClass *xrc = XIVE_ROUTER_GET_CLASS(xrtr);
1197 
1198     return xrc->get_tctx(xrtr, cs);
1199 }
1200 
1201 /*
1202  * By default on P9, the HW CAM line (23bits) is hardwired to :
1203  *
1204  *   0x000||0b1||4Bit chip number||7Bit Thread number.
1205  *
1206  * When the block grouping is enabled, the CAM line is changed to :
1207  *
1208  *   4Bit chip number||0x001||7Bit Thread number.
1209  */
1210 static uint32_t hw_cam_line(uint8_t chip_id, uint8_t tid)
1211 {
1212     return 1 << 11 | (chip_id & 0xf) << 7 | (tid & 0x7f);
1213 }
1214 
1215 static bool xive_presenter_tctx_match_hw(XiveTCTX *tctx,
1216                                          uint8_t nvt_blk, uint32_t nvt_idx)
1217 {
1218     CPUPPCState *env = &POWERPC_CPU(tctx->cs)->env;
1219     uint32_t pir = env->spr_cb[SPR_PIR].default_value;
1220 
1221     return hw_cam_line((pir >> 8) & 0xf, pir & 0x7f) ==
1222         hw_cam_line(nvt_blk, nvt_idx);
1223 }
1224 
1225 /*
1226  * The thread context register words are in big-endian format.
1227  */
1228 static int xive_presenter_tctx_match(XiveTCTX *tctx, uint8_t format,
1229                                      uint8_t nvt_blk, uint32_t nvt_idx,
1230                                      bool cam_ignore, uint32_t logic_serv)
1231 {
1232     uint32_t cam = xive_nvt_cam_line(nvt_blk, nvt_idx);
1233     uint32_t qw3w2 = xive_tctx_word2(&tctx->regs[TM_QW3_HV_PHYS]);
1234     uint32_t qw2w2 = xive_tctx_word2(&tctx->regs[TM_QW2_HV_POOL]);
1235     uint32_t qw1w2 = xive_tctx_word2(&tctx->regs[TM_QW1_OS]);
1236     uint32_t qw0w2 = xive_tctx_word2(&tctx->regs[TM_QW0_USER]);
1237 
1238     /*
1239      * TODO (PowerNV): ignore mode. The low order bits of the NVT
1240      * identifier are ignored in the "CAM" match.
1241      */
1242 
1243     if (format == 0) {
1244         if (cam_ignore == true) {
1245             /*
1246              * F=0 & i=1: Logical server notification (bits ignored at
1247              * the end of the NVT identifier)
1248              */
1249             qemu_log_mask(LOG_UNIMP, "XIVE: no support for LS NVT %x/%x\n",
1250                           nvt_blk, nvt_idx);
1251              return -1;
1252         }
1253 
1254         /* F=0 & i=0: Specific NVT notification */
1255 
1256         /* PHYS ring */
1257         if ((be32_to_cpu(qw3w2) & TM_QW3W2_VT) &&
1258             xive_presenter_tctx_match_hw(tctx, nvt_blk, nvt_idx)) {
1259             return TM_QW3_HV_PHYS;
1260         }
1261 
1262         /* HV POOL ring */
1263         if ((be32_to_cpu(qw2w2) & TM_QW2W2_VP) &&
1264             cam == xive_get_field32(TM_QW2W2_POOL_CAM, qw2w2)) {
1265             return TM_QW2_HV_POOL;
1266         }
1267 
1268         /* OS ring */
1269         if ((be32_to_cpu(qw1w2) & TM_QW1W2_VO) &&
1270             cam == xive_get_field32(TM_QW1W2_OS_CAM, qw1w2)) {
1271             return TM_QW1_OS;
1272         }
1273     } else {
1274         /* F=1 : User level Event-Based Branch (EBB) notification */
1275 
1276         /* USER ring */
1277         if  ((be32_to_cpu(qw1w2) & TM_QW1W2_VO) &&
1278              (cam == xive_get_field32(TM_QW1W2_OS_CAM, qw1w2)) &&
1279              (be32_to_cpu(qw0w2) & TM_QW0W2_VU) &&
1280              (logic_serv == xive_get_field32(TM_QW0W2_LOGIC_SERV, qw0w2))) {
1281             return TM_QW0_USER;
1282         }
1283     }
1284     return -1;
1285 }
1286 
1287 typedef struct XiveTCTXMatch {
1288     XiveTCTX *tctx;
1289     uint8_t ring;
1290 } XiveTCTXMatch;
1291 
1292 static bool xive_presenter_match(XiveRouter *xrtr, uint8_t format,
1293                                  uint8_t nvt_blk, uint32_t nvt_idx,
1294                                  bool cam_ignore, uint8_t priority,
1295                                  uint32_t logic_serv, XiveTCTXMatch *match)
1296 {
1297     CPUState *cs;
1298 
1299     /*
1300      * TODO (PowerNV): handle chip_id overwrite of block field for
1301      * hardwired CAM compares
1302      */
1303 
1304     CPU_FOREACH(cs) {
1305         XiveTCTX *tctx = xive_router_get_tctx(xrtr, cs);
1306         int ring;
1307 
1308         /*
1309          * HW checks that the CPU is enabled in the Physical Thread
1310          * Enable Register (PTER).
1311          */
1312 
1313         /*
1314          * Check the thread context CAM lines and record matches. We
1315          * will handle CPU exception delivery later
1316          */
1317         ring = xive_presenter_tctx_match(tctx, format, nvt_blk, nvt_idx,
1318                                          cam_ignore, logic_serv);
1319         /*
1320          * Save the context and follow on to catch duplicates, that we
1321          * don't support yet.
1322          */
1323         if (ring != -1) {
1324             if (match->tctx) {
1325                 qemu_log_mask(LOG_GUEST_ERROR, "XIVE: already found a thread "
1326                               "context NVT %x/%x\n", nvt_blk, nvt_idx);
1327                 return false;
1328             }
1329 
1330             match->ring = ring;
1331             match->tctx = tctx;
1332         }
1333     }
1334 
1335     if (!match->tctx) {
1336         qemu_log_mask(LOG_UNIMP, "XIVE: NVT %x/%x is not dispatched\n",
1337                       nvt_blk, nvt_idx);
1338         return false;
1339     }
1340 
1341     return true;
1342 }
1343 
1344 /*
1345  * This is our simple Xive Presenter Engine model. It is merged in the
1346  * Router as it does not require an extra object.
1347  *
1348  * It receives notification requests sent by the IVRE to find one
1349  * matching NVT (or more) dispatched on the processor threads. In case
1350  * of a single NVT notification, the process is abreviated and the
1351  * thread is signaled if a match is found. In case of a logical server
1352  * notification (bits ignored at the end of the NVT identifier), the
1353  * IVPE and IVRE select a winning thread using different filters. This
1354  * involves 2 or 3 exchanges on the PowerBus that the model does not
1355  * support.
1356  *
1357  * The parameters represent what is sent on the PowerBus
1358  */
1359 static void xive_presenter_notify(XiveRouter *xrtr, uint8_t format,
1360                                   uint8_t nvt_blk, uint32_t nvt_idx,
1361                                   bool cam_ignore, uint8_t priority,
1362                                   uint32_t logic_serv)
1363 {
1364     XiveNVT nvt;
1365     XiveTCTXMatch match = { .tctx = NULL, .ring = 0 };
1366     bool found;
1367 
1368     /* NVT cache lookup */
1369     if (xive_router_get_nvt(xrtr, nvt_blk, nvt_idx, &nvt)) {
1370         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: no NVT %x/%x\n",
1371                       nvt_blk, nvt_idx);
1372         return;
1373     }
1374 
1375     if (!xive_nvt_is_valid(&nvt)) {
1376         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: NVT %x/%x is invalid\n",
1377                       nvt_blk, nvt_idx);
1378         return;
1379     }
1380 
1381     found = xive_presenter_match(xrtr, format, nvt_blk, nvt_idx, cam_ignore,
1382                                  priority, logic_serv, &match);
1383     if (found) {
1384         ipb_update(&match.tctx->regs[match.ring], priority);
1385         xive_tctx_notify(match.tctx, match.ring);
1386         return;
1387     }
1388 
1389     /* Record the IPB in the associated NVT structure */
1390     ipb_update((uint8_t *) &nvt.w4, priority);
1391     xive_router_write_nvt(xrtr, nvt_blk, nvt_idx, &nvt, 4);
1392 
1393     /*
1394      * If no matching NVT is dispatched on a HW thread :
1395      * - update the NVT structure if backlog is activated
1396      * - escalate (ESe PQ bits and EAS in w4-5) if escalation is
1397      *   activated
1398      */
1399 }
1400 
1401 /*
1402  * An END trigger can come from an event trigger (IPI or HW) or from
1403  * another chip. We don't model the PowerBus but the END trigger
1404  * message has the same parameters than in the function below.
1405  */
1406 static void xive_router_end_notify(XiveRouter *xrtr, uint8_t end_blk,
1407                                    uint32_t end_idx, uint32_t end_data)
1408 {
1409     XiveEND end;
1410     uint8_t priority;
1411     uint8_t format;
1412 
1413     /* END cache lookup */
1414     if (xive_router_get_end(xrtr, end_blk, end_idx, &end)) {
1415         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: No END %x/%x\n", end_blk,
1416                       end_idx);
1417         return;
1418     }
1419 
1420     if (!xive_end_is_valid(&end)) {
1421         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: END %x/%x is invalid\n",
1422                       end_blk, end_idx);
1423         return;
1424     }
1425 
1426     if (xive_end_is_enqueue(&end)) {
1427         xive_end_enqueue(&end, end_data);
1428         /* Enqueuing event data modifies the EQ toggle and index */
1429         xive_router_write_end(xrtr, end_blk, end_idx, &end, 1);
1430     }
1431 
1432     /*
1433      * The W7 format depends on the F bit in W6. It defines the type
1434      * of the notification :
1435      *
1436      *   F=0 : single or multiple NVT notification
1437      *   F=1 : User level Event-Based Branch (EBB) notification, no
1438      *         priority
1439      */
1440     format = xive_get_field32(END_W6_FORMAT_BIT, end.w6);
1441     priority = xive_get_field32(END_W7_F0_PRIORITY, end.w7);
1442 
1443     /* The END is masked */
1444     if (format == 0 && priority == 0xff) {
1445         return;
1446     }
1447 
1448     /*
1449      * Check the END ESn (Event State Buffer for notification) for
1450      * even futher coalescing in the Router
1451      */
1452     if (!xive_end_is_notify(&end)) {
1453         uint8_t pq = xive_get_field32(END_W1_ESn, end.w1);
1454         bool notify = xive_esb_trigger(&pq);
1455 
1456         if (pq != xive_get_field32(END_W1_ESn, end.w1)) {
1457             end.w1 = xive_set_field32(END_W1_ESn, end.w1, pq);
1458             xive_router_write_end(xrtr, end_blk, end_idx, &end, 1);
1459         }
1460 
1461         /* ESn[Q]=1 : end of notification */
1462         if (!notify) {
1463             return;
1464         }
1465     }
1466 
1467     /*
1468      * Follows IVPE notification
1469      */
1470     xive_presenter_notify(xrtr, format,
1471                           xive_get_field32(END_W6_NVT_BLOCK, end.w6),
1472                           xive_get_field32(END_W6_NVT_INDEX, end.w6),
1473                           xive_get_field32(END_W7_F0_IGNORE, end.w7),
1474                           priority,
1475                           xive_get_field32(END_W7_F1_LOG_SERVER_ID, end.w7));
1476 
1477     /* TODO: Auto EOI. */
1478 }
1479 
1480 void xive_router_notify(XiveNotifier *xn, uint32_t lisn)
1481 {
1482     XiveRouter *xrtr = XIVE_ROUTER(xn);
1483     uint8_t eas_blk = XIVE_SRCNO_BLOCK(lisn);
1484     uint32_t eas_idx = XIVE_SRCNO_INDEX(lisn);
1485     XiveEAS eas;
1486 
1487     /* EAS cache lookup */
1488     if (xive_router_get_eas(xrtr, eas_blk, eas_idx, &eas)) {
1489         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: Unknown LISN %x\n", lisn);
1490         return;
1491     }
1492 
1493     /*
1494      * The IVRE checks the State Bit Cache at this point. We skip the
1495      * SBC lookup because the state bits of the sources are modeled
1496      * internally in QEMU.
1497      */
1498 
1499     if (!xive_eas_is_valid(&eas)) {
1500         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: invalid LISN %x\n", lisn);
1501         return;
1502     }
1503 
1504     if (xive_eas_is_masked(&eas)) {
1505         /* Notification completed */
1506         return;
1507     }
1508 
1509     /*
1510      * The event trigger becomes an END trigger
1511      */
1512     xive_router_end_notify(xrtr,
1513                            xive_get_field64(EAS_END_BLOCK, eas.w),
1514                            xive_get_field64(EAS_END_INDEX, eas.w),
1515                            xive_get_field64(EAS_END_DATA,  eas.w));
1516 }
1517 
1518 static void xive_router_class_init(ObjectClass *klass, void *data)
1519 {
1520     DeviceClass *dc = DEVICE_CLASS(klass);
1521     XiveNotifierClass *xnc = XIVE_NOTIFIER_CLASS(klass);
1522 
1523     dc->desc    = "XIVE Router Engine";
1524     xnc->notify = xive_router_notify;
1525 }
1526 
1527 static const TypeInfo xive_router_info = {
1528     .name          = TYPE_XIVE_ROUTER,
1529     .parent        = TYPE_SYS_BUS_DEVICE,
1530     .abstract      = true,
1531     .class_size    = sizeof(XiveRouterClass),
1532     .class_init    = xive_router_class_init,
1533     .interfaces    = (InterfaceInfo[]) {
1534         { TYPE_XIVE_NOTIFIER },
1535         { }
1536     }
1537 };
1538 
1539 void xive_eas_pic_print_info(XiveEAS *eas, uint32_t lisn, Monitor *mon)
1540 {
1541     if (!xive_eas_is_valid(eas)) {
1542         return;
1543     }
1544 
1545     monitor_printf(mon, "  %08x %s end:%02x/%04x data:%08x\n",
1546                    lisn, xive_eas_is_masked(eas) ? "M" : " ",
1547                    (uint8_t)  xive_get_field64(EAS_END_BLOCK, eas->w),
1548                    (uint32_t) xive_get_field64(EAS_END_INDEX, eas->w),
1549                    (uint32_t) xive_get_field64(EAS_END_DATA, eas->w));
1550 }
1551 
1552 /*
1553  * END ESB MMIO loads
1554  */
1555 static uint64_t xive_end_source_read(void *opaque, hwaddr addr, unsigned size)
1556 {
1557     XiveENDSource *xsrc = XIVE_END_SOURCE(opaque);
1558     uint32_t offset = addr & 0xFFF;
1559     uint8_t end_blk;
1560     uint32_t end_idx;
1561     XiveEND end;
1562     uint32_t end_esmask;
1563     uint8_t pq;
1564     uint64_t ret = -1;
1565 
1566     end_blk = xsrc->block_id;
1567     end_idx = addr >> (xsrc->esb_shift + 1);
1568 
1569     if (xive_router_get_end(xsrc->xrtr, end_blk, end_idx, &end)) {
1570         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: No END %x/%x\n", end_blk,
1571                       end_idx);
1572         return -1;
1573     }
1574 
1575     if (!xive_end_is_valid(&end)) {
1576         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: END %x/%x is invalid\n",
1577                       end_blk, end_idx);
1578         return -1;
1579     }
1580 
1581     end_esmask = addr_is_even(addr, xsrc->esb_shift) ? END_W1_ESn : END_W1_ESe;
1582     pq = xive_get_field32(end_esmask, end.w1);
1583 
1584     switch (offset) {
1585     case XIVE_ESB_LOAD_EOI ... XIVE_ESB_LOAD_EOI + 0x7FF:
1586         ret = xive_esb_eoi(&pq);
1587 
1588         /* Forward the source event notification for routing ?? */
1589         break;
1590 
1591     case XIVE_ESB_GET ... XIVE_ESB_GET + 0x3FF:
1592         ret = pq;
1593         break;
1594 
1595     case XIVE_ESB_SET_PQ_00 ... XIVE_ESB_SET_PQ_00 + 0x0FF:
1596     case XIVE_ESB_SET_PQ_01 ... XIVE_ESB_SET_PQ_01 + 0x0FF:
1597     case XIVE_ESB_SET_PQ_10 ... XIVE_ESB_SET_PQ_10 + 0x0FF:
1598     case XIVE_ESB_SET_PQ_11 ... XIVE_ESB_SET_PQ_11 + 0x0FF:
1599         ret = xive_esb_set(&pq, (offset >> 8) & 0x3);
1600         break;
1601     default:
1602         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: invalid END ESB load addr %d\n",
1603                       offset);
1604         return -1;
1605     }
1606 
1607     if (pq != xive_get_field32(end_esmask, end.w1)) {
1608         end.w1 = xive_set_field32(end_esmask, end.w1, pq);
1609         xive_router_write_end(xsrc->xrtr, end_blk, end_idx, &end, 1);
1610     }
1611 
1612     return ret;
1613 }
1614 
1615 /*
1616  * END ESB MMIO stores are invalid
1617  */
1618 static void xive_end_source_write(void *opaque, hwaddr addr,
1619                                   uint64_t value, unsigned size)
1620 {
1621     qemu_log_mask(LOG_GUEST_ERROR, "XIVE: invalid ESB write addr 0x%"
1622                   HWADDR_PRIx"\n", addr);
1623 }
1624 
1625 static const MemoryRegionOps xive_end_source_ops = {
1626     .read = xive_end_source_read,
1627     .write = xive_end_source_write,
1628     .endianness = DEVICE_BIG_ENDIAN,
1629     .valid = {
1630         .min_access_size = 8,
1631         .max_access_size = 8,
1632     },
1633     .impl = {
1634         .min_access_size = 8,
1635         .max_access_size = 8,
1636     },
1637 };
1638 
1639 static void xive_end_source_realize(DeviceState *dev, Error **errp)
1640 {
1641     XiveENDSource *xsrc = XIVE_END_SOURCE(dev);
1642     Object *obj;
1643     Error *local_err = NULL;
1644 
1645     obj = object_property_get_link(OBJECT(dev), "xive", &local_err);
1646     if (!obj) {
1647         error_propagate(errp, local_err);
1648         error_prepend(errp, "required link 'xive' not found: ");
1649         return;
1650     }
1651 
1652     xsrc->xrtr = XIVE_ROUTER(obj);
1653 
1654     if (!xsrc->nr_ends) {
1655         error_setg(errp, "Number of interrupt needs to be greater than 0");
1656         return;
1657     }
1658 
1659     if (xsrc->esb_shift != XIVE_ESB_4K &&
1660         xsrc->esb_shift != XIVE_ESB_64K) {
1661         error_setg(errp, "Invalid ESB shift setting");
1662         return;
1663     }
1664 
1665     /*
1666      * Each END is assigned an even/odd pair of MMIO pages, the even page
1667      * manages the ESn field while the odd page manages the ESe field.
1668      */
1669     memory_region_init_io(&xsrc->esb_mmio, OBJECT(xsrc),
1670                           &xive_end_source_ops, xsrc, "xive.end",
1671                           (1ull << (xsrc->esb_shift + 1)) * xsrc->nr_ends);
1672 }
1673 
1674 static Property xive_end_source_properties[] = {
1675     DEFINE_PROP_UINT8("block-id", XiveENDSource, block_id, 0),
1676     DEFINE_PROP_UINT32("nr-ends", XiveENDSource, nr_ends, 0),
1677     DEFINE_PROP_UINT32("shift", XiveENDSource, esb_shift, XIVE_ESB_64K),
1678     DEFINE_PROP_END_OF_LIST(),
1679 };
1680 
1681 static void xive_end_source_class_init(ObjectClass *klass, void *data)
1682 {
1683     DeviceClass *dc = DEVICE_CLASS(klass);
1684 
1685     dc->desc    = "XIVE END Source";
1686     dc->props   = xive_end_source_properties;
1687     dc->realize = xive_end_source_realize;
1688 }
1689 
1690 static const TypeInfo xive_end_source_info = {
1691     .name          = TYPE_XIVE_END_SOURCE,
1692     .parent        = TYPE_DEVICE,
1693     .instance_size = sizeof(XiveENDSource),
1694     .class_init    = xive_end_source_class_init,
1695 };
1696 
1697 /*
1698  * XIVE Notifier
1699  */
1700 static const TypeInfo xive_notifier_info = {
1701     .name = TYPE_XIVE_NOTIFIER,
1702     .parent = TYPE_INTERFACE,
1703     .class_size = sizeof(XiveNotifierClass),
1704 };
1705 
1706 static void xive_register_types(void)
1707 {
1708     type_register_static(&xive_source_info);
1709     type_register_static(&xive_notifier_info);
1710     type_register_static(&xive_router_info);
1711     type_register_static(&xive_end_source_info);
1712     type_register_static(&xive_tctx_info);
1713 }
1714 
1715 type_init(xive_register_types)
1716