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