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