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