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