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