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