xref: /openbmc/qemu/hw/intc/xive.c (revision 2a24e6e394c0badefd1c6b1ecf571f3663236300)
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 "qemu/module.h"
13 #include "qapi/error.h"
14 #include "target/ppc/cpu.h"
15 #include "sysemu/cpus.h"
16 #include "sysemu/dma.h"
17 #include "sysemu/reset.h"
18 #include "hw/qdev-properties.h"
19 #include "migration/vmstate.h"
20 #include "monitor/monitor.h"
21 #include "hw/irq.h"
22 #include "hw/ppc/xive.h"
23 #include "hw/ppc/xive_regs.h"
24 #include "trace.h"
25 
26 /*
27  * XIVE Thread Interrupt Management context
28  */
29 
30 /*
31  * Convert an Interrupt Pending Buffer (IPB) register to a Pending
32  * Interrupt Priority Register (PIPR), which contains the priority of
33  * the most favored pending notification.
34  */
35 static uint8_t ipb_to_pipr(uint8_t ibp)
36 {
37     return ibp ? clz32((uint32_t)ibp << 24) : 0xff;
38 }
39 
40 static uint8_t exception_mask(uint8_t ring)
41 {
42     switch (ring) {
43     case TM_QW1_OS:
44         return TM_QW1_NSR_EO;
45     case TM_QW3_HV_PHYS:
46         return TM_QW3_NSR_HE;
47     default:
48         g_assert_not_reached();
49     }
50 }
51 
52 static qemu_irq xive_tctx_output(XiveTCTX *tctx, uint8_t ring)
53 {
54         switch (ring) {
55         case TM_QW0_USER:
56                 return 0; /* Not supported */
57         case TM_QW1_OS:
58                 return tctx->os_output;
59         case TM_QW2_HV_POOL:
60         case TM_QW3_HV_PHYS:
61                 return tctx->hv_output;
62         default:
63                 return 0;
64         }
65 }
66 
67 static uint64_t xive_tctx_accept(XiveTCTX *tctx, uint8_t ring)
68 {
69     uint8_t *regs = &tctx->regs[ring];
70     uint8_t nsr = regs[TM_NSR];
71     uint8_t mask = exception_mask(ring);
72 
73     qemu_irq_lower(xive_tctx_output(tctx, ring));
74 
75     if (regs[TM_NSR] & mask) {
76         uint8_t cppr = regs[TM_PIPR];
77 
78         regs[TM_CPPR] = cppr;
79 
80         /* Reset the pending buffer bit */
81         regs[TM_IPB] &= ~xive_priority_to_ipb(cppr);
82         regs[TM_PIPR] = ipb_to_pipr(regs[TM_IPB]);
83 
84         /* Drop Exception bit */
85         regs[TM_NSR] &= ~mask;
86 
87         trace_xive_tctx_accept(tctx->cs->cpu_index, ring,
88                                regs[TM_IPB], regs[TM_PIPR],
89                                regs[TM_CPPR], regs[TM_NSR]);
90     }
91 
92     return (nsr << 8) | regs[TM_CPPR];
93 }
94 
95 static void xive_tctx_notify(XiveTCTX *tctx, uint8_t ring)
96 {
97     uint8_t *regs = &tctx->regs[ring];
98 
99     if (regs[TM_PIPR] < regs[TM_CPPR]) {
100         switch (ring) {
101         case TM_QW1_OS:
102             regs[TM_NSR] |= TM_QW1_NSR_EO;
103             break;
104         case TM_QW3_HV_PHYS:
105             regs[TM_NSR] |= (TM_QW3_NSR_HE_PHYS << 6);
106             break;
107         default:
108             g_assert_not_reached();
109         }
110         trace_xive_tctx_notify(tctx->cs->cpu_index, ring,
111                                regs[TM_IPB], regs[TM_PIPR],
112                                regs[TM_CPPR], regs[TM_NSR]);
113         qemu_irq_raise(xive_tctx_output(tctx, ring));
114     }
115 }
116 
117 void xive_tctx_reset_os_signal(XiveTCTX *tctx)
118 {
119     /*
120      * Lower the External interrupt. Used when pulling an OS
121      * context. It is necessary to avoid catching it in the hypervisor
122      * context. It should be raised again when re-pushing the OS
123      * context.
124      */
125     qemu_irq_lower(xive_tctx_output(tctx, TM_QW1_OS));
126 }
127 
128 static void xive_tctx_set_cppr(XiveTCTX *tctx, uint8_t ring, uint8_t cppr)
129 {
130     uint8_t *regs = &tctx->regs[ring];
131 
132     trace_xive_tctx_set_cppr(tctx->cs->cpu_index, ring,
133                              regs[TM_IPB], regs[TM_PIPR],
134                              cppr, regs[TM_NSR]);
135 
136     if (cppr > XIVE_PRIORITY_MAX) {
137         cppr = 0xff;
138     }
139 
140     tctx->regs[ring + TM_CPPR] = cppr;
141 
142     /* CPPR has changed, check if we need to raise a pending exception */
143     xive_tctx_notify(tctx, ring);
144 }
145 
146 void xive_tctx_ipb_update(XiveTCTX *tctx, uint8_t ring, uint8_t ipb)
147 {
148     uint8_t *regs = &tctx->regs[ring];
149 
150     regs[TM_IPB] |= ipb;
151     regs[TM_PIPR] = ipb_to_pipr(regs[TM_IPB]);
152     xive_tctx_notify(tctx, ring);
153 }
154 
155 /*
156  * XIVE Thread Interrupt Management Area (TIMA)
157  */
158 
159 static void xive_tm_set_hv_cppr(XivePresenter *xptr, XiveTCTX *tctx,
160                                 hwaddr offset, uint64_t value, unsigned size)
161 {
162     xive_tctx_set_cppr(tctx, TM_QW3_HV_PHYS, value & 0xff);
163 }
164 
165 static uint64_t xive_tm_ack_hv_reg(XivePresenter *xptr, XiveTCTX *tctx,
166                                    hwaddr offset, unsigned size)
167 {
168     return xive_tctx_accept(tctx, TM_QW3_HV_PHYS);
169 }
170 
171 static uint64_t xive_tm_pull_pool_ctx(XivePresenter *xptr, XiveTCTX *tctx,
172                                       hwaddr offset, unsigned size)
173 {
174     uint32_t qw2w2_prev = xive_tctx_word2(&tctx->regs[TM_QW2_HV_POOL]);
175     uint32_t qw2w2;
176 
177     qw2w2 = xive_set_field32(TM_QW2W2_VP, qw2w2_prev, 0);
178     memcpy(&tctx->regs[TM_QW2_HV_POOL + TM_WORD2], &qw2w2, 4);
179     return qw2w2;
180 }
181 
182 static void xive_tm_vt_push(XivePresenter *xptr, XiveTCTX *tctx, hwaddr offset,
183                             uint64_t value, unsigned size)
184 {
185     tctx->regs[TM_QW3_HV_PHYS + TM_WORD2] = value & 0xff;
186 }
187 
188 static uint64_t xive_tm_vt_poll(XivePresenter *xptr, XiveTCTX *tctx,
189                                 hwaddr offset, unsigned size)
190 {
191     return tctx->regs[TM_QW3_HV_PHYS + TM_WORD2] & 0xff;
192 }
193 
194 /*
195  * Define an access map for each page of the TIMA that we will use in
196  * the memory region ops to filter values when doing loads and stores
197  * of raw registers values
198  *
199  * Registers accessibility bits :
200  *
201  *    0x0 - no access
202  *    0x1 - write only
203  *    0x2 - read only
204  *    0x3 - read/write
205  */
206 
207 static const uint8_t xive_tm_hw_view[] = {
208     3, 0, 0, 0,   0, 0, 0, 0,   3, 3, 3, 3,   0, 0, 0, 0, /* QW-0 User */
209     3, 3, 3, 3,   3, 3, 0, 2,   3, 3, 3, 3,   0, 0, 0, 0, /* QW-1 OS   */
210     0, 0, 3, 3,   0, 0, 0, 0,   3, 3, 3, 3,   0, 0, 0, 0, /* QW-2 POOL */
211     3, 3, 3, 3,   0, 3, 0, 2,   3, 0, 0, 3,   3, 3, 3, 0, /* QW-3 PHYS */
212 };
213 
214 static const uint8_t xive_tm_hv_view[] = {
215     3, 0, 0, 0,   0, 0, 0, 0,   3, 3, 3, 3,   0, 0, 0, 0, /* QW-0 User */
216     3, 3, 3, 3,   3, 3, 0, 2,   3, 3, 3, 3,   0, 0, 0, 0, /* QW-1 OS   */
217     0, 0, 3, 3,   0, 0, 0, 0,   0, 3, 3, 3,   0, 0, 0, 0, /* QW-2 POOL */
218     3, 3, 3, 3,   0, 3, 0, 2,   3, 0, 0, 3,   0, 0, 0, 0, /* QW-3 PHYS */
219 };
220 
221 static const uint8_t xive_tm_os_view[] = {
222     3, 0, 0, 0,   0, 0, 0, 0,   3, 3, 3, 3,   0, 0, 0, 0, /* QW-0 User */
223     2, 3, 2, 2,   2, 2, 0, 2,   0, 0, 0, 0,   0, 0, 0, 0, /* QW-1 OS   */
224     0, 0, 0, 0,   0, 0, 0, 0,   0, 0, 0, 0,   0, 0, 0, 0, /* QW-2 POOL */
225     0, 0, 0, 0,   0, 0, 0, 0,   0, 0, 0, 0,   0, 0, 0, 0, /* QW-3 PHYS */
226 };
227 
228 static const uint8_t xive_tm_user_view[] = {
229     3, 0, 0, 0,   0, 0, 0, 0,   0, 0, 0, 0,   0, 0, 0, 0, /* QW-0 User */
230     0, 0, 0, 0,   0, 0, 0, 0,   0, 0, 0, 0,   0, 0, 0, 0, /* QW-1 OS   */
231     0, 0, 0, 0,   0, 0, 0, 0,   0, 0, 0, 0,   0, 0, 0, 0, /* QW-2 POOL */
232     0, 0, 0, 0,   0, 0, 0, 0,   0, 0, 0, 0,   0, 0, 0, 0, /* QW-3 PHYS */
233 };
234 
235 /*
236  * Overall TIMA access map for the thread interrupt management context
237  * registers
238  */
239 static const uint8_t *xive_tm_views[] = {
240     [XIVE_TM_HW_PAGE]   = xive_tm_hw_view,
241     [XIVE_TM_HV_PAGE]   = xive_tm_hv_view,
242     [XIVE_TM_OS_PAGE]   = xive_tm_os_view,
243     [XIVE_TM_USER_PAGE] = xive_tm_user_view,
244 };
245 
246 /*
247  * Computes a register access mask for a given offset in the TIMA
248  */
249 static uint64_t xive_tm_mask(hwaddr offset, unsigned size, bool write)
250 {
251     uint8_t page_offset = (offset >> TM_SHIFT) & 0x3;
252     uint8_t reg_offset = offset & TM_REG_OFFSET;
253     uint8_t reg_mask = write ? 0x1 : 0x2;
254     uint64_t mask = 0x0;
255     int i;
256 
257     for (i = 0; i < size; i++) {
258         if (xive_tm_views[page_offset][reg_offset + i] & reg_mask) {
259             mask |= (uint64_t) 0xff << (8 * (size - i - 1));
260         }
261     }
262 
263     return mask;
264 }
265 
266 static void xive_tm_raw_write(XiveTCTX *tctx, hwaddr offset, uint64_t value,
267                               unsigned size)
268 {
269     uint8_t ring_offset = offset & TM_RING_OFFSET;
270     uint8_t reg_offset = offset & TM_REG_OFFSET;
271     uint64_t mask = xive_tm_mask(offset, size, true);
272     int i;
273 
274     /*
275      * Only 4 or 8 bytes stores are allowed and the User ring is
276      * excluded
277      */
278     if (size < 4 || !mask || ring_offset == TM_QW0_USER) {
279         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: invalid write access at TIMA @%"
280                       HWADDR_PRIx"\n", offset);
281         return;
282     }
283 
284     /*
285      * Use the register offset for the raw values and filter out
286      * reserved values
287      */
288     for (i = 0; i < size; i++) {
289         uint8_t byte_mask = (mask >> (8 * (size - i - 1)));
290         if (byte_mask) {
291             tctx->regs[reg_offset + i] = (value >> (8 * (size - i - 1))) &
292                 byte_mask;
293         }
294     }
295 }
296 
297 static uint64_t xive_tm_raw_read(XiveTCTX *tctx, hwaddr offset, unsigned size)
298 {
299     uint8_t ring_offset = offset & TM_RING_OFFSET;
300     uint8_t reg_offset = offset & TM_REG_OFFSET;
301     uint64_t mask = xive_tm_mask(offset, size, false);
302     uint64_t ret;
303     int i;
304 
305     /*
306      * Only 4 or 8 bytes loads are allowed and the User ring is
307      * excluded
308      */
309     if (size < 4 || !mask || ring_offset == TM_QW0_USER) {
310         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: invalid read access at TIMA @%"
311                       HWADDR_PRIx"\n", offset);
312         return -1;
313     }
314 
315     /* Use the register offset for the raw values */
316     ret = 0;
317     for (i = 0; i < size; i++) {
318         ret |= (uint64_t) tctx->regs[reg_offset + i] << (8 * (size - i - 1));
319     }
320 
321     /* filter out reserved values */
322     return ret & mask;
323 }
324 
325 /*
326  * The TM context is mapped twice within each page. Stores and loads
327  * to the first mapping below 2K write and read the specified values
328  * without modification. The second mapping above 2K performs specific
329  * state changes (side effects) in addition to setting/returning the
330  * interrupt management area context of the processor thread.
331  */
332 static uint64_t xive_tm_ack_os_reg(XivePresenter *xptr, XiveTCTX *tctx,
333                                    hwaddr offset, unsigned size)
334 {
335     return xive_tctx_accept(tctx, TM_QW1_OS);
336 }
337 
338 static void xive_tm_set_os_cppr(XivePresenter *xptr, XiveTCTX *tctx,
339                                 hwaddr offset, uint64_t value, unsigned size)
340 {
341     xive_tctx_set_cppr(tctx, TM_QW1_OS, value & 0xff);
342 }
343 
344 /*
345  * Adjust the IPB to allow a CPU to process event queues of other
346  * priorities during one physical interrupt cycle.
347  */
348 static void xive_tm_set_os_pending(XivePresenter *xptr, XiveTCTX *tctx,
349                                    hwaddr offset, uint64_t value, unsigned size)
350 {
351     xive_tctx_ipb_update(tctx, TM_QW1_OS, xive_priority_to_ipb(value & 0xff));
352 }
353 
354 static void xive_os_cam_decode(uint32_t cam, uint8_t *nvt_blk,
355                                uint32_t *nvt_idx, bool *vo)
356 {
357     if (nvt_blk) {
358         *nvt_blk = xive_nvt_blk(cam);
359     }
360     if (nvt_idx) {
361         *nvt_idx = xive_nvt_idx(cam);
362     }
363     if (vo) {
364         *vo = !!(cam & TM_QW1W2_VO);
365     }
366 }
367 
368 static uint32_t xive_tctx_get_os_cam(XiveTCTX *tctx, uint8_t *nvt_blk,
369                                      uint32_t *nvt_idx, bool *vo)
370 {
371     uint32_t qw1w2 = xive_tctx_word2(&tctx->regs[TM_QW1_OS]);
372     uint32_t cam = be32_to_cpu(qw1w2);
373 
374     xive_os_cam_decode(cam, nvt_blk, nvt_idx, vo);
375     return qw1w2;
376 }
377 
378 static void xive_tctx_set_os_cam(XiveTCTX *tctx, uint32_t qw1w2)
379 {
380     memcpy(&tctx->regs[TM_QW1_OS + TM_WORD2], &qw1w2, 4);
381 }
382 
383 static uint64_t xive_tm_pull_os_ctx(XivePresenter *xptr, XiveTCTX *tctx,
384                                     hwaddr offset, unsigned size)
385 {
386     uint32_t qw1w2;
387     uint32_t qw1w2_new;
388     uint8_t nvt_blk;
389     uint32_t nvt_idx;
390     bool vo;
391 
392     qw1w2 = xive_tctx_get_os_cam(tctx, &nvt_blk, &nvt_idx, &vo);
393 
394     if (!vo) {
395         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: pulling invalid NVT %x/%x !?\n",
396                       nvt_blk, nvt_idx);
397     }
398 
399     /* Invalidate CAM line */
400     qw1w2_new = xive_set_field32(TM_QW1W2_VO, qw1w2, 0);
401     xive_tctx_set_os_cam(tctx, qw1w2_new);
402 
403     xive_tctx_reset_os_signal(tctx);
404     return qw1w2;
405 }
406 
407 static void xive_tctx_need_resend(XiveRouter *xrtr, XiveTCTX *tctx,
408                                   uint8_t nvt_blk, uint32_t nvt_idx)
409 {
410     XiveNVT nvt;
411     uint8_t ipb;
412 
413     /*
414      * Grab the associated NVT to pull the pending bits, and merge
415      * them with the IPB of the thread interrupt context registers
416      */
417     if (xive_router_get_nvt(xrtr, nvt_blk, nvt_idx, &nvt)) {
418         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: invalid NVT %x/%x\n",
419                           nvt_blk, nvt_idx);
420         return;
421     }
422 
423     ipb = xive_get_field32(NVT_W4_IPB, nvt.w4);
424 
425     if (ipb) {
426         /* Reset the NVT value */
427         nvt.w4 = xive_set_field32(NVT_W4_IPB, nvt.w4, 0);
428         xive_router_write_nvt(xrtr, nvt_blk, nvt_idx, &nvt, 4);
429     }
430     /*
431      * Always call xive_tctx_ipb_update(). Even if there were no
432      * escalation triggered, there could be a pending interrupt which
433      * was saved when the context was pulled and that we need to take
434      * into account by recalculating the PIPR (which is not
435      * saved/restored).
436      * It will also raise the External interrupt signal if needed.
437      */
438     xive_tctx_ipb_update(tctx, TM_QW1_OS, ipb);
439 }
440 
441 /*
442  * Updating the OS CAM line can trigger a resend of interrupt
443  */
444 static void xive_tm_push_os_ctx(XivePresenter *xptr, XiveTCTX *tctx,
445                                 hwaddr offset, uint64_t value, unsigned size)
446 {
447     uint32_t cam = value;
448     uint32_t qw1w2 = cpu_to_be32(cam);
449     uint8_t nvt_blk;
450     uint32_t nvt_idx;
451     bool vo;
452 
453     xive_os_cam_decode(cam, &nvt_blk, &nvt_idx, &vo);
454 
455     /* First update the registers */
456     xive_tctx_set_os_cam(tctx, qw1w2);
457 
458     /* Check the interrupt pending bits */
459     if (vo) {
460         xive_tctx_need_resend(XIVE_ROUTER(xptr), tctx, nvt_blk, nvt_idx);
461     }
462 }
463 
464 static __attribute__((unused)) uint32_t xive_presenter_get_config(XivePresenter *xptr)
465 {
466     XivePresenterClass *xpc = XIVE_PRESENTER_GET_CLASS(xptr);
467 
468     return xpc->get_config(xptr);
469 }
470 
471 /*
472  * Define a mapping of "special" operations depending on the TIMA page
473  * offset and the size of the operation.
474  */
475 typedef struct XiveTmOp {
476     uint8_t  page_offset;
477     uint32_t op_offset;
478     unsigned size;
479     void     (*write_handler)(XivePresenter *xptr, XiveTCTX *tctx,
480                               hwaddr offset,
481                               uint64_t value, unsigned size);
482     uint64_t (*read_handler)(XivePresenter *xptr, XiveTCTX *tctx, hwaddr offset,
483                              unsigned size);
484 } XiveTmOp;
485 
486 static const XiveTmOp xive_tm_operations[] = {
487     /*
488      * MMIOs below 2K : raw values and special operations without side
489      * effects
490      */
491     { XIVE_TM_OS_PAGE, TM_QW1_OS + TM_CPPR,   1, xive_tm_set_os_cppr, NULL },
492     { XIVE_TM_HV_PAGE, TM_QW1_OS + TM_WORD2,     4, xive_tm_push_os_ctx, NULL },
493     { XIVE_TM_HV_PAGE, TM_QW3_HV_PHYS + TM_CPPR, 1, xive_tm_set_hv_cppr, NULL },
494     { XIVE_TM_HV_PAGE, TM_QW3_HV_PHYS + TM_WORD2, 1, xive_tm_vt_push, NULL },
495     { XIVE_TM_HV_PAGE, TM_QW3_HV_PHYS + TM_WORD2, 1, NULL, xive_tm_vt_poll },
496 
497     /* MMIOs above 2K : special operations with side effects */
498     { XIVE_TM_OS_PAGE, TM_SPC_ACK_OS_REG,     2, NULL, xive_tm_ack_os_reg },
499     { XIVE_TM_OS_PAGE, TM_SPC_SET_OS_PENDING, 1, xive_tm_set_os_pending, NULL },
500     { XIVE_TM_HV_PAGE, TM_SPC_PULL_OS_CTX,    4, NULL, xive_tm_pull_os_ctx },
501     { XIVE_TM_HV_PAGE, TM_SPC_PULL_OS_CTX,    8, NULL, xive_tm_pull_os_ctx },
502     { XIVE_TM_HV_PAGE, TM_SPC_ACK_HV_REG,     2, NULL, xive_tm_ack_hv_reg },
503     { XIVE_TM_HV_PAGE, TM_SPC_PULL_POOL_CTX,  4, NULL, xive_tm_pull_pool_ctx },
504     { XIVE_TM_HV_PAGE, TM_SPC_PULL_POOL_CTX,  8, NULL, xive_tm_pull_pool_ctx },
505 };
506 
507 static const XiveTmOp *xive_tm_find_op(hwaddr offset, unsigned size, bool write)
508 {
509     uint8_t page_offset = (offset >> TM_SHIFT) & 0x3;
510     uint32_t op_offset = offset & TM_ADDRESS_MASK;
511     int i;
512 
513     for (i = 0; i < ARRAY_SIZE(xive_tm_operations); i++) {
514         const XiveTmOp *xto = &xive_tm_operations[i];
515 
516         /* Accesses done from a more privileged TIMA page is allowed */
517         if (xto->page_offset >= page_offset &&
518             xto->op_offset == op_offset &&
519             xto->size == size &&
520             ((write && xto->write_handler) || (!write && xto->read_handler))) {
521             return xto;
522         }
523     }
524     return NULL;
525 }
526 
527 /*
528  * TIMA MMIO handlers
529  */
530 void xive_tctx_tm_write(XivePresenter *xptr, XiveTCTX *tctx, hwaddr offset,
531                         uint64_t value, unsigned size)
532 {
533     const XiveTmOp *xto;
534 
535     trace_xive_tctx_tm_write(offset, size, value);
536 
537     /*
538      * TODO: check V bit in Q[0-3]W2
539      */
540 
541     /*
542      * First, check for special operations in the 2K region
543      */
544     if (offset & TM_SPECIAL_OP) {
545         xto = xive_tm_find_op(offset, size, true);
546         if (!xto) {
547             qemu_log_mask(LOG_GUEST_ERROR, "XIVE: invalid write access at TIMA "
548                           "@%"HWADDR_PRIx"\n", offset);
549         } else {
550             xto->write_handler(xptr, tctx, offset, value, size);
551         }
552         return;
553     }
554 
555     /*
556      * Then, for special operations in the region below 2K.
557      */
558     xto = xive_tm_find_op(offset, size, true);
559     if (xto) {
560         xto->write_handler(xptr, tctx, offset, value, size);
561         return;
562     }
563 
564     /*
565      * Finish with raw access to the register values
566      */
567     xive_tm_raw_write(tctx, offset, value, size);
568 }
569 
570 uint64_t xive_tctx_tm_read(XivePresenter *xptr, XiveTCTX *tctx, hwaddr offset,
571                            unsigned size)
572 {
573     const XiveTmOp *xto;
574     uint64_t ret;
575 
576     /*
577      * TODO: check V bit in Q[0-3]W2
578      */
579 
580     /*
581      * First, check for special operations in the 2K region
582      */
583     if (offset & TM_SPECIAL_OP) {
584         xto = xive_tm_find_op(offset, size, false);
585         if (!xto) {
586             qemu_log_mask(LOG_GUEST_ERROR, "XIVE: invalid read access to TIMA"
587                           "@%"HWADDR_PRIx"\n", offset);
588             return -1;
589         }
590         ret = xto->read_handler(xptr, tctx, offset, size);
591         goto out;
592     }
593 
594     /*
595      * Then, for special operations in the region below 2K.
596      */
597     xto = xive_tm_find_op(offset, size, false);
598     if (xto) {
599         ret = xto->read_handler(xptr, tctx, offset, size);
600         goto out;
601     }
602 
603     /*
604      * Finish with raw access to the register values
605      */
606     ret = xive_tm_raw_read(tctx, offset, size);
607 out:
608     trace_xive_tctx_tm_read(offset, size, ret);
609     return ret;
610 }
611 
612 static char *xive_tctx_ring_print(uint8_t *ring)
613 {
614     uint32_t w2 = xive_tctx_word2(ring);
615 
616     return g_strdup_printf("%02x   %02x  %02x    %02x   %02x  "
617                    "%02x  %02x   %02x  %08x",
618                    ring[TM_NSR], ring[TM_CPPR], ring[TM_IPB], ring[TM_LSMFB],
619                    ring[TM_ACK_CNT], ring[TM_INC], ring[TM_AGE], ring[TM_PIPR],
620                    be32_to_cpu(w2));
621 }
622 
623 static const char * const xive_tctx_ring_names[] = {
624     "USER", "OS", "POOL", "PHYS",
625 };
626 
627 /*
628  * kvm_irqchip_in_kernel() will cause the compiler to turn this
629  * info a nop if CONFIG_KVM isn't defined.
630  */
631 #define xive_in_kernel(xptr)                                            \
632     (kvm_irqchip_in_kernel() &&                                         \
633      ({                                                                 \
634          XivePresenterClass *xpc = XIVE_PRESENTER_GET_CLASS(xptr);      \
635          xpc->in_kernel ? xpc->in_kernel(xptr) : false;                 \
636      }))
637 
638 void xive_tctx_pic_print_info(XiveTCTX *tctx, Monitor *mon)
639 {
640     int cpu_index;
641     int i;
642 
643     /* Skip partially initialized vCPUs. This can happen on sPAPR when vCPUs
644      * are hot plugged or unplugged.
645      */
646     if (!tctx) {
647         return;
648     }
649 
650     cpu_index = tctx->cs ? tctx->cs->cpu_index : -1;
651 
652     if (xive_in_kernel(tctx->xptr)) {
653         Error *local_err = NULL;
654 
655         kvmppc_xive_cpu_synchronize_state(tctx, &local_err);
656         if (local_err) {
657             error_report_err(local_err);
658             return;
659         }
660     }
661 
662     monitor_printf(mon, "CPU[%04x]:   QW   NSR CPPR IPB LSMFB ACK# INC AGE PIPR"
663                    "  W2\n", cpu_index);
664 
665     for (i = 0; i < XIVE_TM_RING_COUNT; i++) {
666         char *s = xive_tctx_ring_print(&tctx->regs[i * XIVE_TM_RING_SIZE]);
667         monitor_printf(mon, "CPU[%04x]: %4s    %s\n", cpu_index,
668                        xive_tctx_ring_names[i], s);
669         g_free(s);
670     }
671 }
672 
673 void xive_tctx_reset(XiveTCTX *tctx)
674 {
675     memset(tctx->regs, 0, sizeof(tctx->regs));
676 
677     /* Set some defaults */
678     tctx->regs[TM_QW1_OS + TM_LSMFB] = 0xFF;
679     tctx->regs[TM_QW1_OS + TM_ACK_CNT] = 0xFF;
680     tctx->regs[TM_QW1_OS + TM_AGE] = 0xFF;
681 
682     /*
683      * Initialize PIPR to 0xFF to avoid phantom interrupts when the
684      * CPPR is first set.
685      */
686     tctx->regs[TM_QW1_OS + TM_PIPR] =
687         ipb_to_pipr(tctx->regs[TM_QW1_OS + TM_IPB]);
688     tctx->regs[TM_QW3_HV_PHYS + TM_PIPR] =
689         ipb_to_pipr(tctx->regs[TM_QW3_HV_PHYS + TM_IPB]);
690 }
691 
692 static void xive_tctx_realize(DeviceState *dev, Error **errp)
693 {
694     XiveTCTX *tctx = XIVE_TCTX(dev);
695     PowerPCCPU *cpu;
696     CPUPPCState *env;
697 
698     assert(tctx->cs);
699     assert(tctx->xptr);
700 
701     cpu = POWERPC_CPU(tctx->cs);
702     env = &cpu->env;
703     switch (PPC_INPUT(env)) {
704     case PPC_FLAGS_INPUT_POWER9:
705         tctx->hv_output = qdev_get_gpio_in(DEVICE(cpu), POWER9_INPUT_HINT);
706         tctx->os_output = qdev_get_gpio_in(DEVICE(cpu), POWER9_INPUT_INT);
707         break;
708 
709     default:
710         error_setg(errp, "XIVE interrupt controller does not support "
711                    "this CPU bus model");
712         return;
713     }
714 
715     /* Connect the presenter to the VCPU (required for CPU hotplug) */
716     if (xive_in_kernel(tctx->xptr)) {
717         if (kvmppc_xive_cpu_connect(tctx, errp) < 0) {
718             return;
719         }
720     }
721 }
722 
723 static int vmstate_xive_tctx_pre_save(void *opaque)
724 {
725     XiveTCTX *tctx = XIVE_TCTX(opaque);
726     Error *local_err = NULL;
727     int ret;
728 
729     if (xive_in_kernel(tctx->xptr)) {
730         ret = kvmppc_xive_cpu_get_state(tctx, &local_err);
731         if (ret < 0) {
732             error_report_err(local_err);
733             return ret;
734         }
735     }
736 
737     return 0;
738 }
739 
740 static int vmstate_xive_tctx_post_load(void *opaque, int version_id)
741 {
742     XiveTCTX *tctx = XIVE_TCTX(opaque);
743     Error *local_err = NULL;
744     int ret;
745 
746     if (xive_in_kernel(tctx->xptr)) {
747         /*
748          * Required for hotplugged CPU, for which the state comes
749          * after all states of the machine.
750          */
751         ret = kvmppc_xive_cpu_set_state(tctx, &local_err);
752         if (ret < 0) {
753             error_report_err(local_err);
754             return ret;
755         }
756     }
757 
758     return 0;
759 }
760 
761 static const VMStateDescription vmstate_xive_tctx = {
762     .name = TYPE_XIVE_TCTX,
763     .version_id = 1,
764     .minimum_version_id = 1,
765     .pre_save = vmstate_xive_tctx_pre_save,
766     .post_load = vmstate_xive_tctx_post_load,
767     .fields = (VMStateField[]) {
768         VMSTATE_BUFFER(regs, XiveTCTX),
769         VMSTATE_END_OF_LIST()
770     },
771 };
772 
773 static Property xive_tctx_properties[] = {
774     DEFINE_PROP_LINK("cpu", XiveTCTX, cs, TYPE_CPU, CPUState *),
775     DEFINE_PROP_LINK("presenter", XiveTCTX, xptr, TYPE_XIVE_PRESENTER,
776                      XivePresenter *),
777     DEFINE_PROP_END_OF_LIST(),
778 };
779 
780 static void xive_tctx_class_init(ObjectClass *klass, void *data)
781 {
782     DeviceClass *dc = DEVICE_CLASS(klass);
783 
784     dc->desc = "XIVE Interrupt Thread Context";
785     dc->realize = xive_tctx_realize;
786     dc->vmsd = &vmstate_xive_tctx;
787     device_class_set_props(dc, xive_tctx_properties);
788     /*
789      * Reason: part of XIVE interrupt controller, needs to be wired up
790      * by xive_tctx_create().
791      */
792     dc->user_creatable = false;
793 }
794 
795 static const TypeInfo xive_tctx_info = {
796     .name          = TYPE_XIVE_TCTX,
797     .parent        = TYPE_DEVICE,
798     .instance_size = sizeof(XiveTCTX),
799     .class_init    = xive_tctx_class_init,
800 };
801 
802 Object *xive_tctx_create(Object *cpu, XivePresenter *xptr, Error **errp)
803 {
804     Object *obj;
805 
806     obj = object_new(TYPE_XIVE_TCTX);
807     object_property_add_child(cpu, TYPE_XIVE_TCTX, obj);
808     object_unref(obj);
809     object_property_set_link(obj, "cpu", cpu, &error_abort);
810     object_property_set_link(obj, "presenter", OBJECT(xptr), &error_abort);
811     if (!qdev_realize(DEVICE(obj), NULL, errp)) {
812         object_unparent(obj);
813         return NULL;
814     }
815     return obj;
816 }
817 
818 void xive_tctx_destroy(XiveTCTX *tctx)
819 {
820     Object *obj = OBJECT(tctx);
821 
822     object_unparent(obj);
823 }
824 
825 /*
826  * XIVE ESB helpers
827  */
828 
829 uint8_t xive_esb_set(uint8_t *pq, uint8_t value)
830 {
831     uint8_t old_pq = *pq & 0x3;
832 
833     *pq &= ~0x3;
834     *pq |= value & 0x3;
835 
836     return old_pq;
837 }
838 
839 bool xive_esb_trigger(uint8_t *pq)
840 {
841     uint8_t old_pq = *pq & 0x3;
842 
843     switch (old_pq) {
844     case XIVE_ESB_RESET:
845         xive_esb_set(pq, XIVE_ESB_PENDING);
846         return true;
847     case XIVE_ESB_PENDING:
848     case XIVE_ESB_QUEUED:
849         xive_esb_set(pq, XIVE_ESB_QUEUED);
850         return false;
851     case XIVE_ESB_OFF:
852         xive_esb_set(pq, XIVE_ESB_OFF);
853         return false;
854     default:
855          g_assert_not_reached();
856     }
857 }
858 
859 bool xive_esb_eoi(uint8_t *pq)
860 {
861     uint8_t old_pq = *pq & 0x3;
862 
863     switch (old_pq) {
864     case XIVE_ESB_RESET:
865     case XIVE_ESB_PENDING:
866         xive_esb_set(pq, XIVE_ESB_RESET);
867         return false;
868     case XIVE_ESB_QUEUED:
869         xive_esb_set(pq, XIVE_ESB_PENDING);
870         return true;
871     case XIVE_ESB_OFF:
872         xive_esb_set(pq, XIVE_ESB_OFF);
873         return false;
874     default:
875          g_assert_not_reached();
876     }
877 }
878 
879 /*
880  * XIVE Interrupt Source (or IVSE)
881  */
882 
883 uint8_t xive_source_esb_get(XiveSource *xsrc, uint32_t srcno)
884 {
885     assert(srcno < xsrc->nr_irqs);
886 
887     return xsrc->status[srcno] & 0x3;
888 }
889 
890 uint8_t xive_source_esb_set(XiveSource *xsrc, uint32_t srcno, uint8_t pq)
891 {
892     assert(srcno < xsrc->nr_irqs);
893 
894     return xive_esb_set(&xsrc->status[srcno], pq);
895 }
896 
897 /*
898  * Returns whether the event notification should be forwarded.
899  */
900 static bool xive_source_lsi_trigger(XiveSource *xsrc, uint32_t srcno)
901 {
902     uint8_t old_pq = xive_source_esb_get(xsrc, srcno);
903 
904     xive_source_set_asserted(xsrc, srcno, true);
905 
906     switch (old_pq) {
907     case XIVE_ESB_RESET:
908         xive_source_esb_set(xsrc, srcno, XIVE_ESB_PENDING);
909         return true;
910     default:
911         return false;
912     }
913 }
914 
915 /*
916  * Sources can be configured with PQ offloading in which case the check
917  * on the PQ state bits of MSIs is disabled
918  */
919 static bool xive_source_esb_disabled(XiveSource *xsrc, uint32_t srcno)
920 {
921     return (xsrc->esb_flags & XIVE_SRC_PQ_DISABLE) &&
922         !xive_source_irq_is_lsi(xsrc, srcno);
923 }
924 
925 /*
926  * Returns whether the event notification should be forwarded.
927  */
928 static bool xive_source_esb_trigger(XiveSource *xsrc, uint32_t srcno)
929 {
930     bool ret;
931 
932     assert(srcno < xsrc->nr_irqs);
933 
934     if (xive_source_esb_disabled(xsrc, srcno)) {
935         return true;
936     }
937 
938     ret = xive_esb_trigger(&xsrc->status[srcno]);
939 
940     if (xive_source_irq_is_lsi(xsrc, srcno) &&
941         xive_source_esb_get(xsrc, srcno) == XIVE_ESB_QUEUED) {
942         qemu_log_mask(LOG_GUEST_ERROR,
943                       "XIVE: queued an event on LSI IRQ %d\n", srcno);
944     }
945 
946     return ret;
947 }
948 
949 /*
950  * Returns whether the event notification should be forwarded.
951  */
952 static bool xive_source_esb_eoi(XiveSource *xsrc, uint32_t srcno)
953 {
954     bool ret;
955 
956     assert(srcno < xsrc->nr_irqs);
957 
958     if (xive_source_esb_disabled(xsrc, srcno)) {
959         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: invalid EOI for IRQ %d\n", srcno);
960         return false;
961     }
962 
963     ret = xive_esb_eoi(&xsrc->status[srcno]);
964 
965     /*
966      * LSI sources do not set the Q bit but they can still be
967      * asserted, in which case we should forward a new event
968      * notification
969      */
970     if (xive_source_irq_is_lsi(xsrc, srcno) &&
971         xive_source_is_asserted(xsrc, srcno)) {
972         ret = xive_source_lsi_trigger(xsrc, srcno);
973     }
974 
975     return ret;
976 }
977 
978 /*
979  * Forward the source event notification to the Router
980  */
981 static void xive_source_notify(XiveSource *xsrc, int srcno)
982 {
983     XiveNotifierClass *xnc = XIVE_NOTIFIER_GET_CLASS(xsrc->xive);
984     bool pq_checked = !xive_source_esb_disabled(xsrc, srcno);
985 
986     if (xnc->notify) {
987         xnc->notify(xsrc->xive, srcno, pq_checked);
988     }
989 }
990 
991 /*
992  * In a two pages ESB MMIO setting, even page is the trigger page, odd
993  * page is for management
994  */
995 static inline bool addr_is_even(hwaddr addr, uint32_t shift)
996 {
997     return !((addr >> shift) & 1);
998 }
999 
1000 static inline bool xive_source_is_trigger_page(XiveSource *xsrc, hwaddr addr)
1001 {
1002     return xive_source_esb_has_2page(xsrc) &&
1003         addr_is_even(addr, xsrc->esb_shift - 1);
1004 }
1005 
1006 /*
1007  * ESB MMIO loads
1008  *                      Trigger page    Management/EOI page
1009  *
1010  * ESB MMIO setting     2 pages         1 or 2 pages
1011  *
1012  * 0x000 .. 0x3FF       -1              EOI and return 0|1
1013  * 0x400 .. 0x7FF       -1              EOI and return 0|1
1014  * 0x800 .. 0xBFF       -1              return PQ
1015  * 0xC00 .. 0xCFF       -1              return PQ and atomically PQ=00
1016  * 0xD00 .. 0xDFF       -1              return PQ and atomically PQ=01
1017  * 0xE00 .. 0xDFF       -1              return PQ and atomically PQ=10
1018  * 0xF00 .. 0xDFF       -1              return PQ and atomically PQ=11
1019  */
1020 static uint64_t xive_source_esb_read(void *opaque, hwaddr addr, unsigned size)
1021 {
1022     XiveSource *xsrc = XIVE_SOURCE(opaque);
1023     uint32_t offset = addr & 0xFFF;
1024     uint32_t srcno = addr >> xsrc->esb_shift;
1025     uint64_t ret = -1;
1026 
1027     /* In a two pages ESB MMIO setting, trigger page should not be read */
1028     if (xive_source_is_trigger_page(xsrc, addr)) {
1029         qemu_log_mask(LOG_GUEST_ERROR,
1030                       "XIVE: invalid load on IRQ %d trigger page at "
1031                       "0x%"HWADDR_PRIx"\n", srcno, addr);
1032         return -1;
1033     }
1034 
1035     switch (offset) {
1036     case XIVE_ESB_LOAD_EOI ... XIVE_ESB_LOAD_EOI + 0x7FF:
1037         ret = xive_source_esb_eoi(xsrc, srcno);
1038 
1039         /* Forward the source event notification for routing */
1040         if (ret) {
1041             xive_source_notify(xsrc, srcno);
1042         }
1043         break;
1044 
1045     case XIVE_ESB_GET ... XIVE_ESB_GET + 0x3FF:
1046         ret = xive_source_esb_get(xsrc, srcno);
1047         break;
1048 
1049     case XIVE_ESB_SET_PQ_00 ... XIVE_ESB_SET_PQ_00 + 0x0FF:
1050     case XIVE_ESB_SET_PQ_01 ... XIVE_ESB_SET_PQ_01 + 0x0FF:
1051     case XIVE_ESB_SET_PQ_10 ... XIVE_ESB_SET_PQ_10 + 0x0FF:
1052     case XIVE_ESB_SET_PQ_11 ... XIVE_ESB_SET_PQ_11 + 0x0FF:
1053         ret = xive_source_esb_set(xsrc, srcno, (offset >> 8) & 0x3);
1054         break;
1055     default:
1056         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: invalid ESB load addr %x\n",
1057                       offset);
1058     }
1059 
1060     trace_xive_source_esb_read(addr, srcno, ret);
1061 
1062     return ret;
1063 }
1064 
1065 /*
1066  * ESB MMIO stores
1067  *                      Trigger page    Management/EOI page
1068  *
1069  * ESB MMIO setting     2 pages         1 or 2 pages
1070  *
1071  * 0x000 .. 0x3FF       Trigger         Trigger
1072  * 0x400 .. 0x7FF       Trigger         EOI
1073  * 0x800 .. 0xBFF       Trigger         undefined
1074  * 0xC00 .. 0xCFF       Trigger         PQ=00
1075  * 0xD00 .. 0xDFF       Trigger         PQ=01
1076  * 0xE00 .. 0xDFF       Trigger         PQ=10
1077  * 0xF00 .. 0xDFF       Trigger         PQ=11
1078  */
1079 static void xive_source_esb_write(void *opaque, hwaddr addr,
1080                                   uint64_t value, unsigned size)
1081 {
1082     XiveSource *xsrc = XIVE_SOURCE(opaque);
1083     uint32_t offset = addr & 0xFFF;
1084     uint32_t srcno = addr >> xsrc->esb_shift;
1085     bool notify = false;
1086 
1087     trace_xive_source_esb_write(addr, srcno, value);
1088 
1089     /* In a two pages ESB MMIO setting, trigger page only triggers */
1090     if (xive_source_is_trigger_page(xsrc, addr)) {
1091         notify = xive_source_esb_trigger(xsrc, srcno);
1092         goto out;
1093     }
1094 
1095     switch (offset) {
1096     case 0 ... 0x3FF:
1097         notify = xive_source_esb_trigger(xsrc, srcno);
1098         break;
1099 
1100     case XIVE_ESB_STORE_EOI ... XIVE_ESB_STORE_EOI + 0x3FF:
1101         if (!(xsrc->esb_flags & XIVE_SRC_STORE_EOI)) {
1102             qemu_log_mask(LOG_GUEST_ERROR,
1103                           "XIVE: invalid Store EOI for IRQ %d\n", srcno);
1104             return;
1105         }
1106 
1107         notify = xive_source_esb_eoi(xsrc, srcno);
1108         break;
1109 
1110     /*
1111      * This is an internal offset used to inject triggers when the PQ
1112      * state bits are not controlled locally. Such as for LSIs when
1113      * under ABT mode.
1114      */
1115     case XIVE_ESB_INJECT ... XIVE_ESB_INJECT + 0x3FF:
1116         notify = true;
1117         break;
1118 
1119     case XIVE_ESB_SET_PQ_00 ... XIVE_ESB_SET_PQ_00 + 0x0FF:
1120     case XIVE_ESB_SET_PQ_01 ... XIVE_ESB_SET_PQ_01 + 0x0FF:
1121     case XIVE_ESB_SET_PQ_10 ... XIVE_ESB_SET_PQ_10 + 0x0FF:
1122     case XIVE_ESB_SET_PQ_11 ... XIVE_ESB_SET_PQ_11 + 0x0FF:
1123         xive_source_esb_set(xsrc, srcno, (offset >> 8) & 0x3);
1124         break;
1125 
1126     default:
1127         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: invalid ESB write addr %x\n",
1128                       offset);
1129         return;
1130     }
1131 
1132 out:
1133     /* Forward the source event notification for routing */
1134     if (notify) {
1135         xive_source_notify(xsrc, srcno);
1136     }
1137 }
1138 
1139 static const MemoryRegionOps xive_source_esb_ops = {
1140     .read = xive_source_esb_read,
1141     .write = xive_source_esb_write,
1142     .endianness = DEVICE_BIG_ENDIAN,
1143     .valid = {
1144         .min_access_size = 8,
1145         .max_access_size = 8,
1146     },
1147     .impl = {
1148         .min_access_size = 8,
1149         .max_access_size = 8,
1150     },
1151 };
1152 
1153 void xive_source_set_irq(void *opaque, int srcno, int val)
1154 {
1155     XiveSource *xsrc = XIVE_SOURCE(opaque);
1156     bool notify = false;
1157 
1158     if (xive_source_irq_is_lsi(xsrc, srcno)) {
1159         if (val) {
1160             notify = xive_source_lsi_trigger(xsrc, srcno);
1161         } else {
1162             xive_source_set_asserted(xsrc, srcno, false);
1163         }
1164     } else {
1165         if (val) {
1166             notify = xive_source_esb_trigger(xsrc, srcno);
1167         }
1168     }
1169 
1170     /* Forward the source event notification for routing */
1171     if (notify) {
1172         xive_source_notify(xsrc, srcno);
1173     }
1174 }
1175 
1176 void xive_source_pic_print_info(XiveSource *xsrc, uint32_t offset, Monitor *mon)
1177 {
1178     int i;
1179 
1180     for (i = 0; i < xsrc->nr_irqs; i++) {
1181         uint8_t pq = xive_source_esb_get(xsrc, i);
1182 
1183         if (pq == XIVE_ESB_OFF) {
1184             continue;
1185         }
1186 
1187         monitor_printf(mon, "  %08x %s %c%c%c\n", i + offset,
1188                        xive_source_irq_is_lsi(xsrc, i) ? "LSI" : "MSI",
1189                        pq & XIVE_ESB_VAL_P ? 'P' : '-',
1190                        pq & XIVE_ESB_VAL_Q ? 'Q' : '-',
1191                        xive_source_is_asserted(xsrc, i) ? 'A' : ' ');
1192     }
1193 }
1194 
1195 static void xive_source_reset(void *dev)
1196 {
1197     XiveSource *xsrc = XIVE_SOURCE(dev);
1198 
1199     /* Do not clear the LSI bitmap */
1200 
1201     /* PQs are initialized to 0b01 (Q=1) which corresponds to "ints off" */
1202     memset(xsrc->status, XIVE_ESB_OFF, xsrc->nr_irqs);
1203 }
1204 
1205 static void xive_source_realize(DeviceState *dev, Error **errp)
1206 {
1207     XiveSource *xsrc = XIVE_SOURCE(dev);
1208     size_t esb_len = xive_source_esb_len(xsrc);
1209 
1210     assert(xsrc->xive);
1211 
1212     if (!xsrc->nr_irqs) {
1213         error_setg(errp, "Number of interrupt needs to be greater than 0");
1214         return;
1215     }
1216 
1217     if (xsrc->esb_shift != XIVE_ESB_4K &&
1218         xsrc->esb_shift != XIVE_ESB_4K_2PAGE &&
1219         xsrc->esb_shift != XIVE_ESB_64K &&
1220         xsrc->esb_shift != XIVE_ESB_64K_2PAGE) {
1221         error_setg(errp, "Invalid ESB shift setting");
1222         return;
1223     }
1224 
1225     xsrc->status = g_malloc0(xsrc->nr_irqs);
1226     xsrc->lsi_map = bitmap_new(xsrc->nr_irqs);
1227 
1228     memory_region_init(&xsrc->esb_mmio, OBJECT(xsrc), "xive.esb", esb_len);
1229     memory_region_init_io(&xsrc->esb_mmio_emulated, OBJECT(xsrc),
1230                           &xive_source_esb_ops, xsrc, "xive.esb-emulated",
1231                           esb_len);
1232     memory_region_add_subregion(&xsrc->esb_mmio, 0, &xsrc->esb_mmio_emulated);
1233 
1234     qemu_register_reset(xive_source_reset, dev);
1235 }
1236 
1237 static const VMStateDescription vmstate_xive_source = {
1238     .name = TYPE_XIVE_SOURCE,
1239     .version_id = 1,
1240     .minimum_version_id = 1,
1241     .fields = (VMStateField[]) {
1242         VMSTATE_UINT32_EQUAL(nr_irqs, XiveSource, NULL),
1243         VMSTATE_VBUFFER_UINT32(status, XiveSource, 1, NULL, nr_irqs),
1244         VMSTATE_END_OF_LIST()
1245     },
1246 };
1247 
1248 /*
1249  * The default XIVE interrupt source setting for the ESB MMIOs is two
1250  * 64k pages without Store EOI, to be in sync with KVM.
1251  */
1252 static Property xive_source_properties[] = {
1253     DEFINE_PROP_UINT64("flags", XiveSource, esb_flags, 0),
1254     DEFINE_PROP_UINT32("nr-irqs", XiveSource, nr_irqs, 0),
1255     DEFINE_PROP_UINT32("shift", XiveSource, esb_shift, XIVE_ESB_64K_2PAGE),
1256     DEFINE_PROP_LINK("xive", XiveSource, xive, TYPE_XIVE_NOTIFIER,
1257                      XiveNotifier *),
1258     DEFINE_PROP_END_OF_LIST(),
1259 };
1260 
1261 static void xive_source_class_init(ObjectClass *klass, void *data)
1262 {
1263     DeviceClass *dc = DEVICE_CLASS(klass);
1264 
1265     dc->desc    = "XIVE Interrupt Source";
1266     device_class_set_props(dc, xive_source_properties);
1267     dc->realize = xive_source_realize;
1268     dc->vmsd    = &vmstate_xive_source;
1269     /*
1270      * Reason: part of XIVE interrupt controller, needs to be wired up,
1271      * e.g. by spapr_xive_instance_init().
1272      */
1273     dc->user_creatable = false;
1274 }
1275 
1276 static const TypeInfo xive_source_info = {
1277     .name          = TYPE_XIVE_SOURCE,
1278     .parent        = TYPE_DEVICE,
1279     .instance_size = sizeof(XiveSource),
1280     .class_init    = xive_source_class_init,
1281 };
1282 
1283 /*
1284  * XiveEND helpers
1285  */
1286 
1287 void xive_end_queue_pic_print_info(XiveEND *end, uint32_t width, Monitor *mon)
1288 {
1289     uint64_t qaddr_base = xive_end_qaddr(end);
1290     uint32_t qsize = xive_get_field32(END_W0_QSIZE, end->w0);
1291     uint32_t qindex = xive_get_field32(END_W1_PAGE_OFF, end->w1);
1292     uint32_t qentries = 1 << (qsize + 10);
1293     int i;
1294 
1295     /*
1296      * print out the [ (qindex - (width - 1)) .. (qindex + 1)] window
1297      */
1298     monitor_printf(mon, " [ ");
1299     qindex = (qindex - (width - 1)) & (qentries - 1);
1300     for (i = 0; i < width; i++) {
1301         uint64_t qaddr = qaddr_base + (qindex << 2);
1302         uint32_t qdata = -1;
1303 
1304         if (dma_memory_read(&address_space_memory, qaddr,
1305                             &qdata, sizeof(qdata), MEMTXATTRS_UNSPECIFIED)) {
1306             qemu_log_mask(LOG_GUEST_ERROR, "XIVE: failed to read EQ @0x%"
1307                           HWADDR_PRIx "\n", qaddr);
1308             return;
1309         }
1310         monitor_printf(mon, "%s%08x ", i == width - 1 ? "^" : "",
1311                        be32_to_cpu(qdata));
1312         qindex = (qindex + 1) & (qentries - 1);
1313     }
1314     monitor_printf(mon, "]");
1315 }
1316 
1317 void xive_end_pic_print_info(XiveEND *end, uint32_t end_idx, Monitor *mon)
1318 {
1319     uint64_t qaddr_base = xive_end_qaddr(end);
1320     uint32_t qindex = xive_get_field32(END_W1_PAGE_OFF, end->w1);
1321     uint32_t qgen = xive_get_field32(END_W1_GENERATION, end->w1);
1322     uint32_t qsize = xive_get_field32(END_W0_QSIZE, end->w0);
1323     uint32_t qentries = 1 << (qsize + 10);
1324 
1325     uint32_t nvt_blk = xive_get_field32(END_W6_NVT_BLOCK, end->w6);
1326     uint32_t nvt_idx = xive_get_field32(END_W6_NVT_INDEX, end->w6);
1327     uint8_t priority = xive_get_field32(END_W7_F0_PRIORITY, end->w7);
1328     uint8_t pq;
1329 
1330     if (!xive_end_is_valid(end)) {
1331         return;
1332     }
1333 
1334     pq = xive_get_field32(END_W1_ESn, end->w1);
1335 
1336     monitor_printf(mon, "  %08x %c%c %c%c%c%c%c%c%c%c prio:%d nvt:%02x/%04x",
1337                    end_idx,
1338                    pq & XIVE_ESB_VAL_P ? 'P' : '-',
1339                    pq & XIVE_ESB_VAL_Q ? 'Q' : '-',
1340                    xive_end_is_valid(end)    ? 'v' : '-',
1341                    xive_end_is_enqueue(end)  ? 'q' : '-',
1342                    xive_end_is_notify(end)   ? 'n' : '-',
1343                    xive_end_is_backlog(end)  ? 'b' : '-',
1344                    xive_end_is_escalate(end) ? 'e' : '-',
1345                    xive_end_is_uncond_escalation(end)   ? 'u' : '-',
1346                    xive_end_is_silent_escalation(end)   ? 's' : '-',
1347                    xive_end_is_firmware(end)   ? 'f' : '-',
1348                    priority, nvt_blk, nvt_idx);
1349 
1350     if (qaddr_base) {
1351         monitor_printf(mon, " eq:@%08"PRIx64"% 6d/%5d ^%d",
1352                        qaddr_base, qindex, qentries, qgen);
1353         xive_end_queue_pic_print_info(end, 6, mon);
1354     }
1355     monitor_printf(mon, "\n");
1356 }
1357 
1358 static void xive_end_enqueue(XiveEND *end, uint32_t data)
1359 {
1360     uint64_t qaddr_base = xive_end_qaddr(end);
1361     uint32_t qsize = xive_get_field32(END_W0_QSIZE, end->w0);
1362     uint32_t qindex = xive_get_field32(END_W1_PAGE_OFF, end->w1);
1363     uint32_t qgen = xive_get_field32(END_W1_GENERATION, end->w1);
1364 
1365     uint64_t qaddr = qaddr_base + (qindex << 2);
1366     uint32_t qdata = cpu_to_be32((qgen << 31) | (data & 0x7fffffff));
1367     uint32_t qentries = 1 << (qsize + 10);
1368 
1369     if (dma_memory_write(&address_space_memory, qaddr,
1370                          &qdata, sizeof(qdata), MEMTXATTRS_UNSPECIFIED)) {
1371         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: failed to write END data @0x%"
1372                       HWADDR_PRIx "\n", qaddr);
1373         return;
1374     }
1375 
1376     qindex = (qindex + 1) & (qentries - 1);
1377     if (qindex == 0) {
1378         qgen ^= 1;
1379         end->w1 = xive_set_field32(END_W1_GENERATION, end->w1, qgen);
1380     }
1381     end->w1 = xive_set_field32(END_W1_PAGE_OFF, end->w1, qindex);
1382 }
1383 
1384 void xive_end_eas_pic_print_info(XiveEND *end, uint32_t end_idx,
1385                                    Monitor *mon)
1386 {
1387     XiveEAS *eas = (XiveEAS *) &end->w4;
1388     uint8_t pq;
1389 
1390     if (!xive_end_is_escalate(end)) {
1391         return;
1392     }
1393 
1394     pq = xive_get_field32(END_W1_ESe, end->w1);
1395 
1396     monitor_printf(mon, "  %08x %c%c %c%c end:%02x/%04x data:%08x\n",
1397                    end_idx,
1398                    pq & XIVE_ESB_VAL_P ? 'P' : '-',
1399                    pq & XIVE_ESB_VAL_Q ? 'Q' : '-',
1400                    xive_eas_is_valid(eas) ? 'V' : ' ',
1401                    xive_eas_is_masked(eas) ? 'M' : ' ',
1402                    (uint8_t)  xive_get_field64(EAS_END_BLOCK, eas->w),
1403                    (uint32_t) xive_get_field64(EAS_END_INDEX, eas->w),
1404                    (uint32_t) xive_get_field64(EAS_END_DATA, eas->w));
1405 }
1406 
1407 /*
1408  * XIVE Router (aka. Virtualization Controller or IVRE)
1409  */
1410 
1411 int xive_router_get_eas(XiveRouter *xrtr, uint8_t eas_blk, uint32_t eas_idx,
1412                         XiveEAS *eas)
1413 {
1414     XiveRouterClass *xrc = XIVE_ROUTER_GET_CLASS(xrtr);
1415 
1416     return xrc->get_eas(xrtr, eas_blk, eas_idx, eas);
1417 }
1418 
1419 static
1420 int xive_router_get_pq(XiveRouter *xrtr, uint8_t eas_blk, uint32_t eas_idx,
1421                        uint8_t *pq)
1422 {
1423     XiveRouterClass *xrc = XIVE_ROUTER_GET_CLASS(xrtr);
1424 
1425     return xrc->get_pq(xrtr, eas_blk, eas_idx, pq);
1426 }
1427 
1428 static
1429 int xive_router_set_pq(XiveRouter *xrtr, uint8_t eas_blk, uint32_t eas_idx,
1430                        uint8_t *pq)
1431 {
1432     XiveRouterClass *xrc = XIVE_ROUTER_GET_CLASS(xrtr);
1433 
1434     return xrc->set_pq(xrtr, eas_blk, eas_idx, pq);
1435 }
1436 
1437 int xive_router_get_end(XiveRouter *xrtr, uint8_t end_blk, uint32_t end_idx,
1438                         XiveEND *end)
1439 {
1440    XiveRouterClass *xrc = XIVE_ROUTER_GET_CLASS(xrtr);
1441 
1442    return xrc->get_end(xrtr, end_blk, end_idx, end);
1443 }
1444 
1445 int xive_router_write_end(XiveRouter *xrtr, uint8_t end_blk, uint32_t end_idx,
1446                           XiveEND *end, uint8_t word_number)
1447 {
1448    XiveRouterClass *xrc = XIVE_ROUTER_GET_CLASS(xrtr);
1449 
1450    return xrc->write_end(xrtr, end_blk, end_idx, end, word_number);
1451 }
1452 
1453 int xive_router_get_nvt(XiveRouter *xrtr, uint8_t nvt_blk, uint32_t nvt_idx,
1454                         XiveNVT *nvt)
1455 {
1456    XiveRouterClass *xrc = XIVE_ROUTER_GET_CLASS(xrtr);
1457 
1458    return xrc->get_nvt(xrtr, nvt_blk, nvt_idx, nvt);
1459 }
1460 
1461 int xive_router_write_nvt(XiveRouter *xrtr, uint8_t nvt_blk, uint32_t nvt_idx,
1462                         XiveNVT *nvt, uint8_t word_number)
1463 {
1464    XiveRouterClass *xrc = XIVE_ROUTER_GET_CLASS(xrtr);
1465 
1466    return xrc->write_nvt(xrtr, nvt_blk, nvt_idx, nvt, word_number);
1467 }
1468 
1469 static int xive_router_get_block_id(XiveRouter *xrtr)
1470 {
1471    XiveRouterClass *xrc = XIVE_ROUTER_GET_CLASS(xrtr);
1472 
1473    return xrc->get_block_id(xrtr);
1474 }
1475 
1476 static void xive_router_realize(DeviceState *dev, Error **errp)
1477 {
1478     XiveRouter *xrtr = XIVE_ROUTER(dev);
1479 
1480     assert(xrtr->xfb);
1481 }
1482 
1483 /*
1484  * Encode the HW CAM line in the block group mode format :
1485  *
1486  *   chip << 19 | 0000000 0 0001 thread (7Bit)
1487  */
1488 static uint32_t xive_tctx_hw_cam_line(XivePresenter *xptr, XiveTCTX *tctx)
1489 {
1490     CPUPPCState *env = &POWERPC_CPU(tctx->cs)->env;
1491     uint32_t pir = env->spr_cb[SPR_PIR].default_value;
1492     uint8_t blk = xive_router_get_block_id(XIVE_ROUTER(xptr));
1493 
1494     return xive_nvt_cam_line(blk, 1 << 7 | (pir & 0x7f));
1495 }
1496 
1497 /*
1498  * The thread context register words are in big-endian format.
1499  */
1500 int xive_presenter_tctx_match(XivePresenter *xptr, XiveTCTX *tctx,
1501                               uint8_t format,
1502                               uint8_t nvt_blk, uint32_t nvt_idx,
1503                               bool cam_ignore, uint32_t logic_serv)
1504 {
1505     uint32_t cam = xive_nvt_cam_line(nvt_blk, nvt_idx);
1506     uint32_t qw3w2 = xive_tctx_word2(&tctx->regs[TM_QW3_HV_PHYS]);
1507     uint32_t qw2w2 = xive_tctx_word2(&tctx->regs[TM_QW2_HV_POOL]);
1508     uint32_t qw1w2 = xive_tctx_word2(&tctx->regs[TM_QW1_OS]);
1509     uint32_t qw0w2 = xive_tctx_word2(&tctx->regs[TM_QW0_USER]);
1510 
1511     /*
1512      * TODO (PowerNV): ignore mode. The low order bits of the NVT
1513      * identifier are ignored in the "CAM" match.
1514      */
1515 
1516     if (format == 0) {
1517         if (cam_ignore == true) {
1518             /*
1519              * F=0 & i=1: Logical server notification (bits ignored at
1520              * the end of the NVT identifier)
1521              */
1522             qemu_log_mask(LOG_UNIMP, "XIVE: no support for LS NVT %x/%x\n",
1523                           nvt_blk, nvt_idx);
1524              return -1;
1525         }
1526 
1527         /* F=0 & i=0: Specific NVT notification */
1528 
1529         /* PHYS ring */
1530         if ((be32_to_cpu(qw3w2) & TM_QW3W2_VT) &&
1531             cam == xive_tctx_hw_cam_line(xptr, tctx)) {
1532             return TM_QW3_HV_PHYS;
1533         }
1534 
1535         /* HV POOL ring */
1536         if ((be32_to_cpu(qw2w2) & TM_QW2W2_VP) &&
1537             cam == xive_get_field32(TM_QW2W2_POOL_CAM, qw2w2)) {
1538             return TM_QW2_HV_POOL;
1539         }
1540 
1541         /* OS ring */
1542         if ((be32_to_cpu(qw1w2) & TM_QW1W2_VO) &&
1543             cam == xive_get_field32(TM_QW1W2_OS_CAM, qw1w2)) {
1544             return TM_QW1_OS;
1545         }
1546     } else {
1547         /* F=1 : User level Event-Based Branch (EBB) notification */
1548 
1549         /* USER ring */
1550         if  ((be32_to_cpu(qw1w2) & TM_QW1W2_VO) &&
1551              (cam == xive_get_field32(TM_QW1W2_OS_CAM, qw1w2)) &&
1552              (be32_to_cpu(qw0w2) & TM_QW0W2_VU) &&
1553              (logic_serv == xive_get_field32(TM_QW0W2_LOGIC_SERV, qw0w2))) {
1554             return TM_QW0_USER;
1555         }
1556     }
1557     return -1;
1558 }
1559 
1560 /*
1561  * This is our simple Xive Presenter Engine model. It is merged in the
1562  * Router as it does not require an extra object.
1563  *
1564  * It receives notification requests sent by the IVRE to find one
1565  * matching NVT (or more) dispatched on the processor threads. In case
1566  * of a single NVT notification, the process is abreviated and the
1567  * thread is signaled if a match is found. In case of a logical server
1568  * notification (bits ignored at the end of the NVT identifier), the
1569  * IVPE and IVRE select a winning thread using different filters. This
1570  * involves 2 or 3 exchanges on the PowerBus that the model does not
1571  * support.
1572  *
1573  * The parameters represent what is sent on the PowerBus
1574  */
1575 bool xive_presenter_notify(XiveFabric *xfb, uint8_t format,
1576                            uint8_t nvt_blk, uint32_t nvt_idx,
1577                            bool cam_ignore, uint8_t priority,
1578                            uint32_t logic_serv)
1579 {
1580     XiveFabricClass *xfc = XIVE_FABRIC_GET_CLASS(xfb);
1581     XiveTCTXMatch match = { .tctx = NULL, .ring = 0 };
1582     int count;
1583 
1584     /*
1585      * Ask the machine to scan the interrupt controllers for a match
1586      */
1587     count = xfc->match_nvt(xfb, format, nvt_blk, nvt_idx, cam_ignore,
1588                            priority, logic_serv, &match);
1589     if (count < 0) {
1590         return false;
1591     }
1592 
1593     /* handle CPU exception delivery */
1594     if (count) {
1595         trace_xive_presenter_notify(nvt_blk, nvt_idx, match.ring);
1596         xive_tctx_ipb_update(match.tctx, match.ring,
1597                              xive_priority_to_ipb(priority));
1598     }
1599 
1600     return !!count;
1601 }
1602 
1603 /*
1604  * Notification using the END ESe/ESn bit (Event State Buffer for
1605  * escalation and notification). Provide further coalescing in the
1606  * Router.
1607  */
1608 static bool xive_router_end_es_notify(XiveRouter *xrtr, uint8_t end_blk,
1609                                       uint32_t end_idx, XiveEND *end,
1610                                       uint32_t end_esmask)
1611 {
1612     uint8_t pq = xive_get_field32(end_esmask, end->w1);
1613     bool notify = xive_esb_trigger(&pq);
1614 
1615     if (pq != xive_get_field32(end_esmask, end->w1)) {
1616         end->w1 = xive_set_field32(end_esmask, end->w1, pq);
1617         xive_router_write_end(xrtr, end_blk, end_idx, end, 1);
1618     }
1619 
1620     /* ESe/n[Q]=1 : end of notification */
1621     return notify;
1622 }
1623 
1624 /*
1625  * An END trigger can come from an event trigger (IPI or HW) or from
1626  * another chip. We don't model the PowerBus but the END trigger
1627  * message has the same parameters than in the function below.
1628  */
1629 static void xive_router_end_notify(XiveRouter *xrtr, uint8_t end_blk,
1630                                    uint32_t end_idx, uint32_t end_data)
1631 {
1632     XiveEND end;
1633     uint8_t priority;
1634     uint8_t format;
1635     uint8_t nvt_blk;
1636     uint32_t nvt_idx;
1637     XiveNVT nvt;
1638     bool found;
1639 
1640     /* END cache lookup */
1641     if (xive_router_get_end(xrtr, end_blk, end_idx, &end)) {
1642         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: No END %x/%x\n", end_blk,
1643                       end_idx);
1644         return;
1645     }
1646 
1647     if (!xive_end_is_valid(&end)) {
1648         trace_xive_router_end_notify(end_blk, end_idx, end_data);
1649         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: END %x/%x is invalid\n",
1650                       end_blk, end_idx);
1651         return;
1652     }
1653 
1654     if (xive_end_is_enqueue(&end)) {
1655         xive_end_enqueue(&end, end_data);
1656         /* Enqueuing event data modifies the EQ toggle and index */
1657         xive_router_write_end(xrtr, end_blk, end_idx, &end, 1);
1658     }
1659 
1660     /*
1661      * When the END is silent, we skip the notification part.
1662      */
1663     if (xive_end_is_silent_escalation(&end)) {
1664         goto do_escalation;
1665     }
1666 
1667     /*
1668      * The W7 format depends on the F bit in W6. It defines the type
1669      * of the notification :
1670      *
1671      *   F=0 : single or multiple NVT notification
1672      *   F=1 : User level Event-Based Branch (EBB) notification, no
1673      *         priority
1674      */
1675     format = xive_get_field32(END_W6_FORMAT_BIT, end.w6);
1676     priority = xive_get_field32(END_W7_F0_PRIORITY, end.w7);
1677 
1678     /* The END is masked */
1679     if (format == 0 && priority == 0xff) {
1680         return;
1681     }
1682 
1683     /*
1684      * Check the END ESn (Event State Buffer for notification) for
1685      * even further coalescing in the Router
1686      */
1687     if (!xive_end_is_notify(&end)) {
1688         /* ESn[Q]=1 : end of notification */
1689         if (!xive_router_end_es_notify(xrtr, end_blk, end_idx,
1690                                        &end, END_W1_ESn)) {
1691             return;
1692         }
1693     }
1694 
1695     /*
1696      * Follows IVPE notification
1697      */
1698     nvt_blk = xive_get_field32(END_W6_NVT_BLOCK, end.w6);
1699     nvt_idx = xive_get_field32(END_W6_NVT_INDEX, end.w6);
1700 
1701     /* NVT cache lookup */
1702     if (xive_router_get_nvt(xrtr, nvt_blk, nvt_idx, &nvt)) {
1703         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: no NVT %x/%x\n",
1704                       nvt_blk, nvt_idx);
1705         return;
1706     }
1707 
1708     if (!xive_nvt_is_valid(&nvt)) {
1709         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: NVT %x/%x is invalid\n",
1710                       nvt_blk, nvt_idx);
1711         return;
1712     }
1713 
1714     found = xive_presenter_notify(xrtr->xfb, format, nvt_blk, nvt_idx,
1715                           xive_get_field32(END_W7_F0_IGNORE, end.w7),
1716                           priority,
1717                           xive_get_field32(END_W7_F1_LOG_SERVER_ID, end.w7));
1718 
1719     /* TODO: Auto EOI. */
1720 
1721     if (found) {
1722         return;
1723     }
1724 
1725     /*
1726      * If no matching NVT is dispatched on a HW thread :
1727      * - specific VP: update the NVT structure if backlog is activated
1728      * - logical server : forward request to IVPE (not supported)
1729      */
1730     if (xive_end_is_backlog(&end)) {
1731         uint8_t ipb;
1732 
1733         if (format == 1) {
1734             qemu_log_mask(LOG_GUEST_ERROR,
1735                           "XIVE: END %x/%x invalid config: F1 & backlog\n",
1736                           end_blk, end_idx);
1737             return;
1738         }
1739         /*
1740          * Record the IPB in the associated NVT structure for later
1741          * use. The presenter will resend the interrupt when the vCPU
1742          * is dispatched again on a HW thread.
1743          */
1744         ipb = xive_get_field32(NVT_W4_IPB, nvt.w4) |
1745             xive_priority_to_ipb(priority);
1746         nvt.w4 = xive_set_field32(NVT_W4_IPB, nvt.w4, ipb);
1747         xive_router_write_nvt(xrtr, nvt_blk, nvt_idx, &nvt, 4);
1748 
1749         /*
1750          * On HW, follows a "Broadcast Backlog" to IVPEs
1751          */
1752     }
1753 
1754 do_escalation:
1755     /*
1756      * If activated, escalate notification using the ESe PQ bits and
1757      * the EAS in w4-5
1758      */
1759     if (!xive_end_is_escalate(&end)) {
1760         return;
1761     }
1762 
1763     /*
1764      * Check the END ESe (Event State Buffer for escalation) for even
1765      * further coalescing in the Router
1766      */
1767     if (!xive_end_is_uncond_escalation(&end)) {
1768         /* ESe[Q]=1 : end of notification */
1769         if (!xive_router_end_es_notify(xrtr, end_blk, end_idx,
1770                                        &end, END_W1_ESe)) {
1771             return;
1772         }
1773     }
1774 
1775     trace_xive_router_end_escalate(end_blk, end_idx,
1776            (uint8_t) xive_get_field32(END_W4_ESC_END_BLOCK, end.w4),
1777            (uint32_t) xive_get_field32(END_W4_ESC_END_INDEX, end.w4),
1778            (uint32_t) xive_get_field32(END_W5_ESC_END_DATA,  end.w5));
1779     /*
1780      * The END trigger becomes an Escalation trigger
1781      */
1782     xive_router_end_notify(xrtr,
1783                            xive_get_field32(END_W4_ESC_END_BLOCK, end.w4),
1784                            xive_get_field32(END_W4_ESC_END_INDEX, end.w4),
1785                            xive_get_field32(END_W5_ESC_END_DATA,  end.w5));
1786 }
1787 
1788 void xive_router_notify(XiveNotifier *xn, uint32_t lisn, bool pq_checked)
1789 {
1790     XiveRouter *xrtr = XIVE_ROUTER(xn);
1791     uint8_t eas_blk = XIVE_EAS_BLOCK(lisn);
1792     uint32_t eas_idx = XIVE_EAS_INDEX(lisn);
1793     XiveEAS eas;
1794 
1795     /* EAS cache lookup */
1796     if (xive_router_get_eas(xrtr, eas_blk, eas_idx, &eas)) {
1797         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: Unknown LISN %x\n", lisn);
1798         return;
1799     }
1800 
1801     if (!pq_checked) {
1802         bool notify;
1803         uint8_t pq;
1804 
1805         /* PQ cache lookup */
1806         if (xive_router_get_pq(xrtr, eas_blk, eas_idx, &pq)) {
1807             /* Set FIR */
1808             g_assert_not_reached();
1809         }
1810 
1811         notify = xive_esb_trigger(&pq);
1812 
1813         if (xive_router_set_pq(xrtr, eas_blk, eas_idx, &pq)) {
1814             /* Set FIR */
1815             g_assert_not_reached();
1816         }
1817 
1818         if (!notify) {
1819             return;
1820         }
1821     }
1822 
1823     if (!xive_eas_is_valid(&eas)) {
1824         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: invalid LISN %x\n", lisn);
1825         return;
1826     }
1827 
1828     if (xive_eas_is_masked(&eas)) {
1829         /* Notification completed */
1830         return;
1831     }
1832 
1833     /*
1834      * The event trigger becomes an END trigger
1835      */
1836     xive_router_end_notify(xrtr,
1837                            xive_get_field64(EAS_END_BLOCK, eas.w),
1838                            xive_get_field64(EAS_END_INDEX, eas.w),
1839                            xive_get_field64(EAS_END_DATA,  eas.w));
1840 }
1841 
1842 static Property xive_router_properties[] = {
1843     DEFINE_PROP_LINK("xive-fabric", XiveRouter, xfb,
1844                      TYPE_XIVE_FABRIC, XiveFabric *),
1845     DEFINE_PROP_END_OF_LIST(),
1846 };
1847 
1848 static void xive_router_class_init(ObjectClass *klass, void *data)
1849 {
1850     DeviceClass *dc = DEVICE_CLASS(klass);
1851     XiveNotifierClass *xnc = XIVE_NOTIFIER_CLASS(klass);
1852 
1853     dc->desc    = "XIVE Router Engine";
1854     device_class_set_props(dc, xive_router_properties);
1855     /* Parent is SysBusDeviceClass. No need to call its realize hook */
1856     dc->realize = xive_router_realize;
1857     xnc->notify = xive_router_notify;
1858 }
1859 
1860 static const TypeInfo xive_router_info = {
1861     .name          = TYPE_XIVE_ROUTER,
1862     .parent        = TYPE_SYS_BUS_DEVICE,
1863     .abstract      = true,
1864     .instance_size = sizeof(XiveRouter),
1865     .class_size    = sizeof(XiveRouterClass),
1866     .class_init    = xive_router_class_init,
1867     .interfaces    = (InterfaceInfo[]) {
1868         { TYPE_XIVE_NOTIFIER },
1869         { TYPE_XIVE_PRESENTER },
1870         { }
1871     }
1872 };
1873 
1874 void xive_eas_pic_print_info(XiveEAS *eas, uint32_t lisn, Monitor *mon)
1875 {
1876     if (!xive_eas_is_valid(eas)) {
1877         return;
1878     }
1879 
1880     monitor_printf(mon, "  %08x %s end:%02x/%04x data:%08x\n",
1881                    lisn, xive_eas_is_masked(eas) ? "M" : " ",
1882                    (uint8_t)  xive_get_field64(EAS_END_BLOCK, eas->w),
1883                    (uint32_t) xive_get_field64(EAS_END_INDEX, eas->w),
1884                    (uint32_t) xive_get_field64(EAS_END_DATA, eas->w));
1885 }
1886 
1887 /*
1888  * END ESB MMIO loads
1889  */
1890 static uint64_t xive_end_source_read(void *opaque, hwaddr addr, unsigned size)
1891 {
1892     XiveENDSource *xsrc = XIVE_END_SOURCE(opaque);
1893     uint32_t offset = addr & 0xFFF;
1894     uint8_t end_blk;
1895     uint32_t end_idx;
1896     XiveEND end;
1897     uint32_t end_esmask;
1898     uint8_t pq;
1899     uint64_t ret = -1;
1900 
1901     /*
1902      * The block id should be deduced from the load address on the END
1903      * ESB MMIO but our model only supports a single block per XIVE chip.
1904      */
1905     end_blk = xive_router_get_block_id(xsrc->xrtr);
1906     end_idx = addr >> (xsrc->esb_shift + 1);
1907 
1908     trace_xive_end_source_read(end_blk, end_idx, addr);
1909 
1910     if (xive_router_get_end(xsrc->xrtr, end_blk, end_idx, &end)) {
1911         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: No END %x/%x\n", end_blk,
1912                       end_idx);
1913         return -1;
1914     }
1915 
1916     if (!xive_end_is_valid(&end)) {
1917         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: END %x/%x is invalid\n",
1918                       end_blk, end_idx);
1919         return -1;
1920     }
1921 
1922     end_esmask = addr_is_even(addr, xsrc->esb_shift) ? END_W1_ESn : END_W1_ESe;
1923     pq = xive_get_field32(end_esmask, end.w1);
1924 
1925     switch (offset) {
1926     case XIVE_ESB_LOAD_EOI ... XIVE_ESB_LOAD_EOI + 0x7FF:
1927         ret = xive_esb_eoi(&pq);
1928 
1929         /* Forward the source event notification for routing ?? */
1930         break;
1931 
1932     case XIVE_ESB_GET ... XIVE_ESB_GET + 0x3FF:
1933         ret = pq;
1934         break;
1935 
1936     case XIVE_ESB_SET_PQ_00 ... XIVE_ESB_SET_PQ_00 + 0x0FF:
1937     case XIVE_ESB_SET_PQ_01 ... XIVE_ESB_SET_PQ_01 + 0x0FF:
1938     case XIVE_ESB_SET_PQ_10 ... XIVE_ESB_SET_PQ_10 + 0x0FF:
1939     case XIVE_ESB_SET_PQ_11 ... XIVE_ESB_SET_PQ_11 + 0x0FF:
1940         ret = xive_esb_set(&pq, (offset >> 8) & 0x3);
1941         break;
1942     default:
1943         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: invalid END ESB load addr %d\n",
1944                       offset);
1945         return -1;
1946     }
1947 
1948     if (pq != xive_get_field32(end_esmask, end.w1)) {
1949         end.w1 = xive_set_field32(end_esmask, end.w1, pq);
1950         xive_router_write_end(xsrc->xrtr, end_blk, end_idx, &end, 1);
1951     }
1952 
1953     return ret;
1954 }
1955 
1956 /*
1957  * END ESB MMIO stores are invalid
1958  */
1959 static void xive_end_source_write(void *opaque, hwaddr addr,
1960                                   uint64_t value, unsigned size)
1961 {
1962     qemu_log_mask(LOG_GUEST_ERROR, "XIVE: invalid ESB write addr 0x%"
1963                   HWADDR_PRIx"\n", addr);
1964 }
1965 
1966 static const MemoryRegionOps xive_end_source_ops = {
1967     .read = xive_end_source_read,
1968     .write = xive_end_source_write,
1969     .endianness = DEVICE_BIG_ENDIAN,
1970     .valid = {
1971         .min_access_size = 8,
1972         .max_access_size = 8,
1973     },
1974     .impl = {
1975         .min_access_size = 8,
1976         .max_access_size = 8,
1977     },
1978 };
1979 
1980 static void xive_end_source_realize(DeviceState *dev, Error **errp)
1981 {
1982     XiveENDSource *xsrc = XIVE_END_SOURCE(dev);
1983 
1984     assert(xsrc->xrtr);
1985 
1986     if (!xsrc->nr_ends) {
1987         error_setg(errp, "Number of interrupt needs to be greater than 0");
1988         return;
1989     }
1990 
1991     if (xsrc->esb_shift != XIVE_ESB_4K &&
1992         xsrc->esb_shift != XIVE_ESB_64K) {
1993         error_setg(errp, "Invalid ESB shift setting");
1994         return;
1995     }
1996 
1997     /*
1998      * Each END is assigned an even/odd pair of MMIO pages, the even page
1999      * manages the ESn field while the odd page manages the ESe field.
2000      */
2001     memory_region_init_io(&xsrc->esb_mmio, OBJECT(xsrc),
2002                           &xive_end_source_ops, xsrc, "xive.end",
2003                           (1ull << (xsrc->esb_shift + 1)) * xsrc->nr_ends);
2004 }
2005 
2006 static Property xive_end_source_properties[] = {
2007     DEFINE_PROP_UINT32("nr-ends", XiveENDSource, nr_ends, 0),
2008     DEFINE_PROP_UINT32("shift", XiveENDSource, esb_shift, XIVE_ESB_64K),
2009     DEFINE_PROP_LINK("xive", XiveENDSource, xrtr, TYPE_XIVE_ROUTER,
2010                      XiveRouter *),
2011     DEFINE_PROP_END_OF_LIST(),
2012 };
2013 
2014 static void xive_end_source_class_init(ObjectClass *klass, void *data)
2015 {
2016     DeviceClass *dc = DEVICE_CLASS(klass);
2017 
2018     dc->desc    = "XIVE END Source";
2019     device_class_set_props(dc, xive_end_source_properties);
2020     dc->realize = xive_end_source_realize;
2021     /*
2022      * Reason: part of XIVE interrupt controller, needs to be wired up,
2023      * e.g. by spapr_xive_instance_init().
2024      */
2025     dc->user_creatable = false;
2026 }
2027 
2028 static const TypeInfo xive_end_source_info = {
2029     .name          = TYPE_XIVE_END_SOURCE,
2030     .parent        = TYPE_DEVICE,
2031     .instance_size = sizeof(XiveENDSource),
2032     .class_init    = xive_end_source_class_init,
2033 };
2034 
2035 /*
2036  * XIVE Notifier
2037  */
2038 static const TypeInfo xive_notifier_info = {
2039     .name = TYPE_XIVE_NOTIFIER,
2040     .parent = TYPE_INTERFACE,
2041     .class_size = sizeof(XiveNotifierClass),
2042 };
2043 
2044 /*
2045  * XIVE Presenter
2046  */
2047 static const TypeInfo xive_presenter_info = {
2048     .name = TYPE_XIVE_PRESENTER,
2049     .parent = TYPE_INTERFACE,
2050     .class_size = sizeof(XivePresenterClass),
2051 };
2052 
2053 /*
2054  * XIVE Fabric
2055  */
2056 static const TypeInfo xive_fabric_info = {
2057     .name = TYPE_XIVE_FABRIC,
2058     .parent = TYPE_INTERFACE,
2059     .class_size = sizeof(XiveFabricClass),
2060 };
2061 
2062 static void xive_register_types(void)
2063 {
2064     type_register_static(&xive_fabric_info);
2065     type_register_static(&xive_source_info);
2066     type_register_static(&xive_notifier_info);
2067     type_register_static(&xive_presenter_info);
2068     type_register_static(&xive_router_info);
2069     type_register_static(&xive_end_source_info);
2070     type_register_static(&xive_tctx_info);
2071 }
2072 
2073 type_init(xive_register_types)
2074