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