xref: /openbmc/qemu/hw/intc/xive2.c (revision 370ea4a4b6fffc30324fc8f8134483e5a749114d)
1 /*
2  * QEMU PowerPC XIVE2 interrupt controller model (POWER10)
3  *
4  * Copyright (c) 2019-2024, 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 "hw/qdev-properties.h"
17 #include "hw/ppc/xive.h"
18 #include "hw/ppc/xive2.h"
19 #include "hw/ppc/xive2_regs.h"
20 #include "trace.h"
21 
22 static void xive2_router_end_notify(Xive2Router *xrtr, uint8_t end_blk,
23                                     uint32_t end_idx, uint32_t end_data,
24                                     bool redistribute);
25 
26 static int xive2_tctx_get_nvp_indexes(XiveTCTX *tctx, uint8_t ring,
27                                       uint8_t *nvp_blk, uint32_t *nvp_idx);
28 
29 uint32_t xive2_router_get_config(Xive2Router *xrtr)
30 {
31     Xive2RouterClass *xrc = XIVE2_ROUTER_GET_CLASS(xrtr);
32 
33     return xrc->get_config(xrtr);
34 }
35 
36 static int xive2_router_get_block_id(Xive2Router *xrtr)
37 {
38    Xive2RouterClass *xrc = XIVE2_ROUTER_GET_CLASS(xrtr);
39 
40    return xrc->get_block_id(xrtr);
41 }
42 
43 static uint64_t xive2_nvp_reporting_addr(Xive2Nvp *nvp)
44 {
45     uint64_t cache_addr;
46 
47     cache_addr = xive_get_field32(NVP2_W6_REPORTING_LINE, nvp->w6) << 24 |
48         xive_get_field32(NVP2_W7_REPORTING_LINE, nvp->w7);
49     cache_addr <<= 8; /* aligned on a cache line pair */
50     return cache_addr;
51 }
52 
53 static uint32_t xive2_nvgc_get_backlog(Xive2Nvgc *nvgc, uint8_t priority)
54 {
55     uint32_t val = 0;
56     uint8_t *ptr, i;
57 
58     if (priority > 7) {
59         return 0;
60     }
61 
62     /*
63      * The per-priority backlog counters are 24-bit and the structure
64      * is stored in big endian. NVGC is 32-bytes long, so 24-bytes from
65      * w2, which fits 8 priorities * 24-bits per priority.
66      */
67     ptr = (uint8_t *)&nvgc->w2 + priority * 3;
68     for (i = 0; i < 3; i++, ptr++) {
69         val = (val << 8) + *ptr;
70     }
71     return val;
72 }
73 
74 static void xive2_nvgc_set_backlog(Xive2Nvgc *nvgc, uint8_t priority,
75                                    uint32_t val)
76 {
77     uint8_t *ptr, i;
78     uint32_t shift;
79 
80     if (priority > 7) {
81         return;
82     }
83 
84     if (val > 0xFFFFFF) {
85         val = 0xFFFFFF;
86     }
87     /*
88      * The per-priority backlog counters are 24-bit and the structure
89      * is stored in big endian
90      */
91     ptr = (uint8_t *)&nvgc->w2 + priority * 3;
92     for (i = 0; i < 3; i++, ptr++) {
93         shift = 8 * (2 - i);
94         *ptr = (val >> shift) & 0xFF;
95     }
96 }
97 
98 uint64_t xive2_presenter_nvgc_backlog_op(XivePresenter *xptr,
99                                          bool crowd,
100                                          uint8_t blk, uint32_t idx,
101                                          uint16_t offset, uint16_t val)
102 {
103     Xive2Router *xrtr = XIVE2_ROUTER(xptr);
104     uint8_t priority = GETFIELD(NVx_BACKLOG_PRIO, offset);
105     uint8_t op = GETFIELD(NVx_BACKLOG_OP, offset);
106     Xive2Nvgc nvgc;
107     uint32_t count, old_count;
108 
109     if (xive2_router_get_nvgc(xrtr, crowd, blk, idx, &nvgc)) {
110         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: No %s %x/%x\n",
111                       crowd ? "NVC" : "NVG", blk, idx);
112         return -1;
113     }
114     if (!xive2_nvgc_is_valid(&nvgc)) {
115         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: Invalid NVG %x/%x\n", blk, idx);
116         return -1;
117     }
118 
119     old_count = xive2_nvgc_get_backlog(&nvgc, priority);
120     count = old_count;
121     /*
122      * op:
123      * 0b00 => increment
124      * 0b01 => decrement
125      * 0b1- => read
126      */
127     if (op == 0b00 || op == 0b01) {
128         if (op == 0b00) {
129             count += val;
130         } else {
131             if (count > val) {
132                 count -= val;
133             } else {
134                 count = 0;
135             }
136         }
137         xive2_nvgc_set_backlog(&nvgc, priority, count);
138         xive2_router_write_nvgc(xrtr, crowd, blk, idx, &nvgc);
139     }
140     trace_xive_nvgc_backlog_op(crowd, blk, idx, op, priority, old_count);
141     return old_count;
142 }
143 
144 uint64_t xive2_presenter_nvp_backlog_op(XivePresenter *xptr,
145                                         uint8_t blk, uint32_t idx,
146                                         uint16_t offset)
147 {
148     Xive2Router *xrtr = XIVE2_ROUTER(xptr);
149     uint8_t priority = GETFIELD(NVx_BACKLOG_PRIO, offset);
150     uint8_t op = GETFIELD(NVx_BACKLOG_OP, offset);
151     Xive2Nvp nvp;
152     uint8_t ipb, old_ipb, rc;
153 
154     if (xive2_router_get_nvp(xrtr, blk, idx, &nvp)) {
155         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: No NVP %x/%x\n", blk, idx);
156         return -1;
157     }
158     if (!xive2_nvp_is_valid(&nvp)) {
159         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: Invalid NVP %x/%x\n", blk, idx);
160         return -1;
161     }
162 
163     old_ipb = xive_get_field32(NVP2_W2_IPB, nvp.w2);
164     ipb = old_ipb;
165     /*
166      * op:
167      * 0b00 => set priority bit
168      * 0b01 => reset priority bit
169      * 0b1- => read
170      */
171     if (op == 0b00 || op == 0b01) {
172         if (op == 0b00) {
173             ipb |= xive_priority_to_ipb(priority);
174         } else {
175             ipb &= ~xive_priority_to_ipb(priority);
176         }
177         nvp.w2 = xive_set_field32(NVP2_W2_IPB, nvp.w2, ipb);
178         xive2_router_write_nvp(xrtr, blk, idx, &nvp, 2);
179     }
180     rc = !!(old_ipb & xive_priority_to_ipb(priority));
181     trace_xive_nvp_backlog_op(blk, idx, op, priority, rc);
182     return rc;
183 }
184 
185 void xive2_eas_pic_print_info(Xive2Eas *eas, uint32_t lisn, GString *buf)
186 {
187     if (!xive2_eas_is_valid(eas)) {
188         return;
189     }
190 
191     g_string_append_printf(buf, "  %08x %s end:%02x/%04x data:%08x\n",
192                            lisn, xive2_eas_is_masked(eas) ? "M" : " ",
193                            (uint8_t)  xive_get_field64(EAS2_END_BLOCK, eas->w),
194                            (uint32_t) xive_get_field64(EAS2_END_INDEX, eas->w),
195                            (uint32_t) xive_get_field64(EAS2_END_DATA, eas->w));
196 }
197 
198 #define XIVE2_QSIZE_CHUNK_CL    128
199 #define XIVE2_QSIZE_CHUNK_4k   4096
200 /* Calculate max number of queue entries for an END */
201 static uint32_t xive2_end_get_qentries(Xive2End *end)
202 {
203     uint32_t w3 = end->w3;
204     uint32_t qsize = xive_get_field32(END2_W3_QSIZE, w3);
205     if (xive_get_field32(END2_W3_CL, w3)) {
206         g_assert(qsize <= 4);
207         return (XIVE2_QSIZE_CHUNK_CL << qsize) / sizeof(uint32_t);
208     } else {
209         g_assert(qsize <= 12);
210         return (XIVE2_QSIZE_CHUNK_4k << qsize) / sizeof(uint32_t);
211     }
212 }
213 
214 void xive2_end_queue_pic_print_info(Xive2End *end, uint32_t width, GString *buf)
215 {
216     uint64_t qaddr_base = xive2_end_qaddr(end);
217     uint32_t qindex = xive_get_field32(END2_W1_PAGE_OFF, end->w1);
218     uint32_t qentries = xive2_end_get_qentries(end);
219     int i;
220 
221     /*
222      * print out the [ (qindex - (width - 1)) .. (qindex + 1)] window
223      */
224     g_string_append_printf(buf, " [ ");
225     qindex = (qindex - (width - 1)) & (qentries - 1);
226     for (i = 0; i < width; i++) {
227         uint64_t qaddr = qaddr_base + (qindex << 2);
228         uint32_t qdata = -1;
229 
230         if (dma_memory_read(&address_space_memory, qaddr, &qdata,
231                             sizeof(qdata), MEMTXATTRS_UNSPECIFIED)) {
232             qemu_log_mask(LOG_GUEST_ERROR, "XIVE: failed to read EQ @0x%"
233                           HWADDR_PRIx "\n", qaddr);
234             return;
235         }
236         g_string_append_printf(buf, "%s%08x ", i == width - 1 ? "^" : "",
237                                be32_to_cpu(qdata));
238         qindex = (qindex + 1) & (qentries - 1);
239     }
240     g_string_append_printf(buf, "]");
241 }
242 
243 void xive2_end_pic_print_info(Xive2End *end, uint32_t end_idx, GString *buf)
244 {
245     uint64_t qaddr_base = xive2_end_qaddr(end);
246     uint32_t qindex = xive_get_field32(END2_W1_PAGE_OFF, end->w1);
247     uint32_t qgen = xive_get_field32(END2_W1_GENERATION, end->w1);
248     uint32_t qentries = xive2_end_get_qentries(end);
249 
250     uint32_t nvx_blk = xive_get_field32(END2_W6_VP_BLOCK, end->w6);
251     uint32_t nvx_idx = xive_get_field32(END2_W6_VP_OFFSET, end->w6);
252     uint8_t priority = xive_get_field32(END2_W7_F0_PRIORITY, end->w7);
253     uint8_t pq;
254 
255     if (!xive2_end_is_valid(end)) {
256         return;
257     }
258 
259     pq = xive_get_field32(END2_W1_ESn, end->w1);
260 
261     g_string_append_printf(buf,
262                            "  %08x %c%c %c%c%c%c%c%c%c%c%c%c%c %c%c "
263                            "prio:%d nvp:%02x/%04x",
264                            end_idx,
265                            pq & XIVE_ESB_VAL_P ? 'P' : '-',
266                            pq & XIVE_ESB_VAL_Q ? 'Q' : '-',
267                            xive2_end_is_valid(end)    ? 'v' : '-',
268                            xive2_end_is_enqueue(end)  ? 'q' : '-',
269                            xive2_end_is_notify(end)   ? 'n' : '-',
270                            xive2_end_is_backlog(end)  ? 'b' : '-',
271                            xive2_end_is_precluded_escalation(end) ? 'p' : '-',
272                            xive2_end_is_escalate(end) ? 'e' : '-',
273                            xive2_end_is_escalate_end(end) ? 'N' : '-',
274                            xive2_end_is_uncond_escalation(end)   ? 'u' : '-',
275                            xive2_end_is_silent_escalation(end)   ? 's' : '-',
276                            xive2_end_is_firmware1(end)   ? 'f' : '-',
277                            xive2_end_is_firmware2(end)   ? 'F' : '-',
278                            xive2_end_is_ignore(end) ? 'i' : '-',
279                            xive2_end_is_crowd(end)  ? 'c' : '-',
280                            priority, nvx_blk, nvx_idx);
281 
282     if (qaddr_base) {
283         g_string_append_printf(buf, " eq:@%08"PRIx64"% 6d/%5d ^%d",
284                                qaddr_base, qindex, qentries, qgen);
285         xive2_end_queue_pic_print_info(end, 6, buf);
286     }
287     g_string_append_c(buf, '\n');
288 }
289 
290 void xive2_end_eas_pic_print_info(Xive2End *end, uint32_t end_idx,
291                                   GString *buf)
292 {
293     Xive2Eas *eas = (Xive2Eas *) &end->w4;
294     uint8_t pq;
295 
296     if (!xive2_end_is_escalate(end)) {
297         return;
298     }
299 
300     pq = xive_get_field32(END2_W1_ESe, end->w1);
301 
302     g_string_append_printf(buf, "  %08x %c%c %c%c end:%02x/%04x data:%08x\n",
303                            end_idx,
304                            pq & XIVE_ESB_VAL_P ? 'P' : '-',
305                            pq & XIVE_ESB_VAL_Q ? 'Q' : '-',
306                            xive2_eas_is_valid(eas) ? 'v' : ' ',
307                            xive2_eas_is_masked(eas) ? 'M' : ' ',
308                            (uint8_t)  xive_get_field64(EAS2_END_BLOCK, eas->w),
309                            (uint32_t) xive_get_field64(EAS2_END_INDEX, eas->w),
310                            (uint32_t) xive_get_field64(EAS2_END_DATA, eas->w));
311 }
312 
313 void xive2_nvp_pic_print_info(Xive2Nvp *nvp, uint32_t nvp_idx, GString *buf)
314 {
315     uint8_t  eq_blk = xive_get_field32(NVP2_W5_VP_END_BLOCK, nvp->w5);
316     uint32_t eq_idx = xive_get_field32(NVP2_W5_VP_END_INDEX, nvp->w5);
317     uint64_t cache_line = xive2_nvp_reporting_addr(nvp);
318 
319     if (!xive2_nvp_is_valid(nvp)) {
320         return;
321     }
322 
323     g_string_append_printf(buf, "  %08x end:%02x/%04x IPB:%02x PGoFirst:%02x",
324                            nvp_idx, eq_blk, eq_idx,
325                            xive_get_field32(NVP2_W2_IPB, nvp->w2),
326                            xive_get_field32(NVP2_W0_PGOFIRST, nvp->w0));
327     if (cache_line) {
328         g_string_append_printf(buf, "  reporting CL:%016"PRIx64, cache_line);
329     }
330 
331     /*
332      * When the NVP is HW controlled, more fields are updated
333      */
334     if (xive2_nvp_is_hw(nvp)) {
335         g_string_append_printf(buf, " CPPR:%02x",
336                                xive_get_field32(NVP2_W2_CPPR, nvp->w2));
337         if (xive2_nvp_is_co(nvp)) {
338             g_string_append_printf(buf, " CO:%04x",
339                                    xive_get_field32(NVP2_W1_CO_THRID, nvp->w1));
340         }
341     }
342     g_string_append_c(buf, '\n');
343 }
344 
345 void xive2_nvgc_pic_print_info(Xive2Nvgc *nvgc, uint32_t nvgc_idx, GString *buf)
346 {
347     uint8_t i;
348 
349     if (!xive2_nvgc_is_valid(nvgc)) {
350         return;
351     }
352 
353     g_string_append_printf(buf, "  %08x PGoNext:%02x bklog: ", nvgc_idx,
354                            xive_get_field32(NVGC2_W0_PGONEXT, nvgc->w0));
355     for (i = 0; i <= XIVE_PRIORITY_MAX; i++) {
356         g_string_append_printf(buf, "[%d]=0x%x ",
357                                i, xive2_nvgc_get_backlog(nvgc, i));
358     }
359     g_string_append_printf(buf, "\n");
360 }
361 
362 static void xive2_end_enqueue(Xive2End *end, uint32_t data)
363 {
364     uint64_t qaddr_base = xive2_end_qaddr(end);
365     uint32_t qindex = xive_get_field32(END2_W1_PAGE_OFF, end->w1);
366     uint32_t qgen = xive_get_field32(END2_W1_GENERATION, end->w1);
367 
368     uint64_t qaddr = qaddr_base + (qindex << 2);
369     uint32_t qdata = cpu_to_be32((qgen << 31) | (data & 0x7fffffff));
370     uint32_t qentries = xive2_end_get_qentries(end);
371 
372     if (dma_memory_write(&address_space_memory, qaddr, &qdata, sizeof(qdata),
373                          MEMTXATTRS_UNSPECIFIED)) {
374         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: failed to write END data @0x%"
375                       HWADDR_PRIx "\n", qaddr);
376         return;
377     }
378 
379     qindex = (qindex + 1) & (qentries - 1);
380     if (qindex == 0) {
381         qgen ^= 1;
382         end->w1 = xive_set_field32(END2_W1_GENERATION, end->w1, qgen);
383 
384         /* Set gen flipped to 1, it gets reset on a cache watch operation */
385         end->w1 = xive_set_field32(END2_W1_GEN_FLIPPED, end->w1, 1);
386     }
387     end->w1 = xive_set_field32(END2_W1_PAGE_OFF, end->w1, qindex);
388 }
389 
390 static void xive2_pgofnext(uint8_t *nvgc_blk, uint32_t *nvgc_idx,
391                            uint8_t next_level)
392 {
393     uint32_t mask, next_idx;
394     uint8_t next_blk;
395 
396     /*
397      * Adjust the block and index of a VP for the next group/crowd
398      * size (PGofFirst/PGofNext field in the NVP and NVGC structures).
399      *
400      * The 6-bit group level is split into a 2-bit crowd and 4-bit
401      * group levels. Encoding is similar. However, we don't support
402      * crowd size of 8. So a crowd level of 0b11 is bumped to a crowd
403      * size of 16.
404      */
405     next_blk = NVx_CROWD_LVL(next_level);
406     if (next_blk == 3) {
407         next_blk = 4;
408     }
409     mask = (1 << next_blk) - 1;
410     *nvgc_blk &= ~mask;
411     *nvgc_blk |= mask >> 1;
412 
413     next_idx = NVx_GROUP_LVL(next_level);
414     mask = (1 << next_idx) - 1;
415     *nvgc_idx &= ~mask;
416     *nvgc_idx |= mask >> 1;
417 }
418 
419 /*
420  * Scan the group chain and return the highest priority and group
421  * level of pending group interrupts.
422  */
423 static uint8_t xive2_presenter_backlog_scan(XivePresenter *xptr,
424                                             uint8_t nvx_blk, uint32_t nvx_idx,
425                                             uint8_t first_group,
426                                             uint8_t *out_level)
427 {
428     Xive2Router *xrtr = XIVE2_ROUTER(xptr);
429     uint32_t nvgc_idx;
430     uint32_t current_level, count;
431     uint8_t nvgc_blk, prio;
432     Xive2Nvgc nvgc;
433 
434     for (prio = 0; prio <= XIVE_PRIORITY_MAX; prio++) {
435         current_level = first_group & 0x3F;
436         nvgc_blk = nvx_blk;
437         nvgc_idx = nvx_idx;
438 
439         while (current_level) {
440             xive2_pgofnext(&nvgc_blk, &nvgc_idx, current_level);
441 
442             if (xive2_router_get_nvgc(xrtr, NVx_CROWD_LVL(current_level),
443                                       nvgc_blk, nvgc_idx, &nvgc)) {
444                 qemu_log_mask(LOG_GUEST_ERROR, "XIVE: No NVGC %x/%x\n",
445                               nvgc_blk, nvgc_idx);
446                 return 0xFF;
447             }
448             if (!xive2_nvgc_is_valid(&nvgc)) {
449                 qemu_log_mask(LOG_GUEST_ERROR, "XIVE: Invalid NVGC %x/%x\n",
450                               nvgc_blk, nvgc_idx);
451                 return 0xFF;
452             }
453 
454             count = xive2_nvgc_get_backlog(&nvgc, prio);
455             if (count) {
456                 *out_level = current_level;
457                 return prio;
458             }
459             current_level = xive_get_field32(NVGC2_W0_PGONEXT, nvgc.w0) & 0x3F;
460         }
461     }
462     return 0xFF;
463 }
464 
465 static void xive2_presenter_backlog_decr(XivePresenter *xptr,
466                                          uint8_t nvx_blk, uint32_t nvx_idx,
467                                          uint8_t group_prio,
468                                          uint8_t group_level)
469 {
470     Xive2Router *xrtr = XIVE2_ROUTER(xptr);
471     uint32_t nvgc_idx, count;
472     uint8_t nvgc_blk;
473     Xive2Nvgc nvgc;
474 
475     nvgc_blk = nvx_blk;
476     nvgc_idx = nvx_idx;
477     xive2_pgofnext(&nvgc_blk, &nvgc_idx, group_level);
478 
479     if (xive2_router_get_nvgc(xrtr, NVx_CROWD_LVL(group_level),
480                               nvgc_blk, nvgc_idx, &nvgc)) {
481         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: No NVGC %x/%x\n",
482                       nvgc_blk, nvgc_idx);
483         return;
484     }
485     if (!xive2_nvgc_is_valid(&nvgc)) {
486         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: Invalid NVGC %x/%x\n",
487                       nvgc_blk, nvgc_idx);
488         return;
489     }
490     count = xive2_nvgc_get_backlog(&nvgc, group_prio);
491     if (!count) {
492         return;
493     }
494     xive2_nvgc_set_backlog(&nvgc, group_prio, count - 1);
495     xive2_router_write_nvgc(xrtr, NVx_CROWD_LVL(group_level),
496                             nvgc_blk, nvgc_idx, &nvgc);
497 }
498 
499 /*
500  * XIVE Thread Interrupt Management Area (TIMA) - Gen2 mode
501  *
502  * TIMA Gen2 VP “save & restore” (S&R) indicated by H bit next to V bit
503  *
504  *   - if a context is enabled with the H bit set, the VP context
505  *     information is retrieved from the NVP structure (“check out”)
506  *     and stored back on a context pull (“check in”), the SW receives
507  *     the same context pull information as on P9
508  *
509  *   - the H bit cannot be changed while the V bit is set, i.e. a
510  *     context cannot be set up in the TIMA and then be “pushed” into
511  *     the NVP by changing the H bit while the context is enabled
512  */
513 
514 static void xive2_tctx_save_ctx(Xive2Router *xrtr, XiveTCTX *tctx,
515                                 uint8_t nvp_blk, uint32_t nvp_idx,
516                                 uint8_t ring)
517 {
518     CPUPPCState *env = &POWERPC_CPU(tctx->cs)->env;
519     uint32_t pir = env->spr_cb[SPR_PIR].default_value;
520     Xive2Nvp nvp;
521     uint8_t *regs = &tctx->regs[ring];
522 
523     if (xive2_router_get_nvp(xrtr, nvp_blk, nvp_idx, &nvp)) {
524         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: No NVP %x/%x\n",
525                           nvp_blk, nvp_idx);
526         return;
527     }
528 
529     if (!xive2_nvp_is_valid(&nvp)) {
530         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: invalid NVP %x/%x\n",
531                       nvp_blk, nvp_idx);
532         return;
533     }
534 
535     if (!xive2_nvp_is_hw(&nvp)) {
536         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: NVP %x/%x is not HW owned\n",
537                       nvp_blk, nvp_idx);
538         return;
539     }
540 
541     if (!xive2_nvp_is_co(&nvp)) {
542         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: NVP %x/%x is not checkout\n",
543                       nvp_blk, nvp_idx);
544         return;
545     }
546 
547     if (xive_get_field32(NVP2_W1_CO_THRID_VALID, nvp.w1) &&
548         xive_get_field32(NVP2_W1_CO_THRID, nvp.w1) != pir) {
549         qemu_log_mask(LOG_GUEST_ERROR,
550                       "XIVE: NVP %x/%x invalid checkout Thread %x\n",
551                       nvp_blk, nvp_idx, pir);
552         return;
553     }
554 
555     nvp.w2 = xive_set_field32(NVP2_W2_IPB, nvp.w2, regs[TM_IPB]);
556     nvp.w2 = xive_set_field32(NVP2_W2_CPPR, nvp.w2, regs[TM_CPPR]);
557     if (nvp.w0 & NVP2_W0_L) {
558         /*
559          * Typically not used. If LSMFB is restored with 0, it will
560          * force a backlog rescan
561          */
562         nvp.w2 = xive_set_field32(NVP2_W2_LSMFB, nvp.w2, regs[TM_LSMFB]);
563     }
564     if (nvp.w0 & NVP2_W0_G) {
565         nvp.w2 = xive_set_field32(NVP2_W2_LGS, nvp.w2, regs[TM_LGS]);
566     }
567     if (nvp.w0 & NVP2_W0_T) {
568         nvp.w2 = xive_set_field32(NVP2_W2_T, nvp.w2, regs[TM_T]);
569     }
570     xive2_router_write_nvp(xrtr, nvp_blk, nvp_idx, &nvp, 2);
571 
572     nvp.w1 = xive_set_field32(NVP2_W1_CO, nvp.w1, 0);
573     /* NVP2_W1_CO_THRID_VALID only set once */
574     nvp.w1 = xive_set_field32(NVP2_W1_CO_THRID, nvp.w1, 0xFFFF);
575     xive2_router_write_nvp(xrtr, nvp_blk, nvp_idx, &nvp, 1);
576 }
577 
578 static void xive2_cam_decode(uint32_t cam, uint8_t *nvp_blk,
579                              uint32_t *nvp_idx, bool *valid, bool *hw)
580 {
581     *nvp_blk = xive2_nvp_blk(cam);
582     *nvp_idx = xive2_nvp_idx(cam);
583     *valid = !!(cam & TM2_W2_VALID);
584     *hw = !!(cam & TM2_W2_HW);
585 }
586 
587 /*
588  * Encode the HW CAM line with 7bit or 8bit thread id. The thread id
589  * width and block id width is configurable at the IC level.
590  *
591  *    chipid << 24 | 0000 0000 0000 0000 1 threadid (7Bit)
592  *    chipid << 24 | 0000 0000 0000 0001 threadid   (8Bit)
593  */
594 static uint32_t xive2_tctx_hw_cam_line(XivePresenter *xptr, XiveTCTX *tctx)
595 {
596     Xive2Router *xrtr = XIVE2_ROUTER(xptr);
597     CPUPPCState *env = &POWERPC_CPU(tctx->cs)->env;
598     uint32_t pir = env->spr_cb[SPR_PIR].default_value;
599     uint8_t blk = xive2_router_get_block_id(xrtr);
600     uint8_t tid_shift =
601         xive2_router_get_config(xrtr) & XIVE2_THREADID_8BITS ? 8 : 7;
602     uint8_t tid_mask = (1 << tid_shift) - 1;
603 
604     return xive2_nvp_cam_line(blk, 1 << tid_shift | (pir & tid_mask));
605 }
606 
607 static void xive2_redistribute(Xive2Router *xrtr, XiveTCTX *tctx, uint8_t ring)
608 {
609     uint8_t *sig_regs = xive_tctx_signal_regs(tctx, ring);
610     uint8_t nsr = sig_regs[TM_NSR];
611     uint8_t pipr = sig_regs[TM_PIPR];
612     uint8_t crowd = NVx_CROWD_LVL(nsr);
613     uint8_t group = NVx_GROUP_LVL(nsr);
614     uint8_t nvgc_blk, end_blk, nvp_blk;
615     uint32_t nvgc_idx, end_idx, nvp_idx;
616     Xive2Nvgc nvgc;
617     uint8_t prio_limit;
618     uint32_t cfg;
619 
620     /* redistribution is only for group/crowd interrupts */
621     if (!xive_nsr_indicates_group_exception(ring, nsr)) {
622         return;
623     }
624 
625     /* Don't check return code since ring is expected to be invalidated */
626     xive2_tctx_get_nvp_indexes(tctx, ring, &nvp_blk, &nvp_idx);
627 
628     trace_xive_redistribute(tctx->cs->cpu_index, ring, nvp_blk, nvp_idx);
629 
630     trace_xive_redistribute(tctx->cs->cpu_index, ring, nvp_blk, nvp_idx);
631     /* convert crowd/group to blk/idx */
632     if (group > 0) {
633         nvgc_idx = (nvp_idx & (0xffffffff << group)) |
634                    ((1 << (group - 1)) - 1);
635     } else {
636         nvgc_idx = nvp_idx;
637     }
638 
639     if (crowd > 0) {
640         crowd = (crowd == 3) ? 4 : crowd;
641         nvgc_blk = (nvp_blk & (0xffffffff << crowd)) |
642                    ((1 << (crowd - 1)) - 1);
643     } else {
644         nvgc_blk = nvp_blk;
645     }
646 
647     /* Use blk/idx to retrieve the NVGC */
648     if (xive2_router_get_nvgc(xrtr, crowd, nvgc_blk, nvgc_idx, &nvgc)) {
649         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: no %s %x/%x\n",
650                       crowd ? "NVC" : "NVG", nvgc_blk, nvgc_idx);
651         return;
652     }
653 
654     /* retrieve the END blk/idx from the NVGC */
655     end_blk = xive_get_field32(NVGC2_W1_END_BLK, nvgc.w1);
656     end_idx = xive_get_field32(NVGC2_W1_END_IDX, nvgc.w1);
657 
658     /* determine number of priorities being used */
659     cfg = xive2_router_get_config(xrtr);
660     if (cfg & XIVE2_EN_VP_GRP_PRIORITY) {
661         prio_limit = 1 << GETFIELD(NVGC2_W1_PSIZE, nvgc.w1);
662     } else {
663         prio_limit = 1 << GETFIELD(XIVE2_VP_INT_PRIO, cfg);
664     }
665 
666     /* add priority offset to end index */
667     end_idx += pipr % prio_limit;
668 
669     /* trigger the group END */
670     xive2_router_end_notify(xrtr, end_blk, end_idx, 0, true);
671 
672     /* clear interrupt indication for the context */
673     sig_regs[TM_NSR] = 0;
674     sig_regs[TM_PIPR] = sig_regs[TM_CPPR];
675     xive_tctx_reset_signal(tctx, ring);
676 }
677 
678 static uint64_t xive2_tm_pull_ctx(XivePresenter *xptr, XiveTCTX *tctx,
679                                   hwaddr offset, unsigned size, uint8_t ring)
680 {
681     Xive2Router *xrtr = XIVE2_ROUTER(xptr);
682     uint32_t target_ringw2 = xive_tctx_word2(&tctx->regs[ring]);
683     uint32_t cam = be32_to_cpu(target_ringw2);
684     uint8_t nvp_blk;
685     uint32_t nvp_idx;
686     uint8_t cur_ring;
687     bool valid;
688     bool do_save;
689     uint8_t nsr;
690 
691     xive2_cam_decode(cam, &nvp_blk, &nvp_idx, &valid, &do_save);
692 
693     if (xive2_tctx_get_nvp_indexes(tctx, ring, &nvp_blk, &nvp_idx)) {
694         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: pulling invalid NVP %x/%x !?\n",
695                       nvp_blk, nvp_idx);
696     }
697 
698     /* Invalidate CAM line of requested ring and all lower rings */
699     for (cur_ring = TM_QW0_USER; cur_ring <= ring;
700          cur_ring += XIVE_TM_RING_SIZE) {
701         uint32_t ringw2 = xive_tctx_word2(&tctx->regs[cur_ring]);
702         uint32_t ringw2_new = xive_set_field32(TM2_QW1W2_VO, ringw2, 0);
703         bool is_valid = !!(xive_get_field32(TM2_QW1W2_VO, ringw2));
704         uint8_t *sig_regs;
705 
706         memcpy(&tctx->regs[cur_ring + TM_WORD2], &ringw2_new, 4);
707 
708         /* Skip the rest for USER or invalid contexts */
709         if ((cur_ring == TM_QW0_USER) || !is_valid) {
710             continue;
711         }
712 
713         /* Active group/crowd interrupts need to be redistributed */
714         sig_regs = xive_tctx_signal_regs(tctx, ring);
715         nsr = sig_regs[TM_NSR];
716         if (xive_nsr_indicates_group_exception(cur_ring, nsr)) {
717             /* Ensure ring matches NSR (for HV NSR POOL vs PHYS rings) */
718             if (cur_ring == xive_nsr_exception_ring(cur_ring, nsr)) {
719                 xive2_redistribute(xrtr, tctx, cur_ring);
720             }
721         }
722     }
723 
724     if (xive2_router_get_config(xrtr) & XIVE2_VP_SAVE_RESTORE && do_save) {
725         xive2_tctx_save_ctx(xrtr, tctx, nvp_blk, nvp_idx, ring);
726     }
727 
728     /*
729      * Lower external interrupt line of requested ring and below except for
730      * USER, which doesn't exist.
731      */
732     for (cur_ring = TM_QW1_OS; cur_ring <= ring;
733          cur_ring += XIVE_TM_RING_SIZE) {
734         xive_tctx_reset_signal(tctx, cur_ring);
735     }
736     return target_ringw2;
737 }
738 
739 uint64_t xive2_tm_pull_os_ctx(XivePresenter *xptr, XiveTCTX *tctx,
740                               hwaddr offset, unsigned size)
741 {
742     return xive2_tm_pull_ctx(xptr, tctx, offset, size, TM_QW1_OS);
743 }
744 
745 uint64_t xive2_tm_pull_pool_ctx(XivePresenter *xptr, XiveTCTX *tctx,
746                                 hwaddr offset, unsigned size)
747 {
748     return xive2_tm_pull_ctx(xptr, tctx, offset, size, TM_QW2_HV_POOL);
749 }
750 
751 uint64_t xive2_tm_pull_phys_ctx(XivePresenter *xptr, XiveTCTX *tctx,
752                                 hwaddr offset, unsigned size)
753 {
754     return xive2_tm_pull_ctx(xptr, tctx, offset, size, TM_QW3_HV_PHYS);
755 }
756 
757 #define REPORT_LINE_GEN1_SIZE       16
758 
759 static void xive2_tm_report_line_gen1(XiveTCTX *tctx, uint8_t *data,
760                                       uint8_t size)
761 {
762     uint8_t *regs = tctx->regs;
763 
764     g_assert(size == REPORT_LINE_GEN1_SIZE);
765     memset(data, 0, size);
766     /*
767      * See xive architecture for description of what is saved. It is
768      * hand-picked information to fit in 16 bytes.
769      */
770     data[0x0] = regs[TM_QW3_HV_PHYS + TM_NSR];
771     data[0x1] = regs[TM_QW3_HV_PHYS + TM_CPPR];
772     data[0x2] = regs[TM_QW3_HV_PHYS + TM_IPB];
773     data[0x3] = regs[TM_QW2_HV_POOL + TM_IPB];
774     data[0x4] = regs[TM_QW1_OS + TM_ACK_CNT];
775     data[0x5] = regs[TM_QW3_HV_PHYS + TM_LGS];
776     data[0x6] = 0xFF;
777     data[0x7] = regs[TM_QW3_HV_PHYS + TM_WORD2] & 0x80;
778     data[0x7] |= (regs[TM_QW2_HV_POOL + TM_WORD2] & 0x80) >> 1;
779     data[0x7] |= (regs[TM_QW1_OS + TM_WORD2] & 0x80) >> 2;
780     data[0x7] |= (regs[TM_QW3_HV_PHYS + TM_WORD2] & 0x3);
781     data[0x8] = regs[TM_QW1_OS + TM_NSR];
782     data[0x9] = regs[TM_QW1_OS + TM_CPPR];
783     data[0xA] = regs[TM_QW1_OS + TM_IPB];
784     data[0xB] = regs[TM_QW1_OS + TM_LGS];
785     if (regs[TM_QW0_USER + TM_WORD2] & 0x80) {
786         /*
787          * Logical server extension, except VU bit replaced by EB bit
788          * from NSR
789          */
790         data[0xC] = regs[TM_QW0_USER + TM_WORD2];
791         data[0xC] &= ~0x80;
792         data[0xC] |= regs[TM_QW0_USER + TM_NSR] & 0x80;
793         data[0xD] = regs[TM_QW0_USER + TM_WORD2 + 1];
794         data[0xE] = regs[TM_QW0_USER + TM_WORD2 + 2];
795         data[0xF] = regs[TM_QW0_USER + TM_WORD2 + 3];
796     }
797 }
798 
799 static void xive2_tm_pull_ctx_ol(XivePresenter *xptr, XiveTCTX *tctx,
800                                  hwaddr offset, uint64_t value,
801                                  unsigned size, uint8_t ring)
802 {
803     Xive2Router *xrtr = XIVE2_ROUTER(xptr);
804     uint32_t hw_cam, nvp_idx, xive2_cfg, reserved;
805     uint8_t nvp_blk;
806     Xive2Nvp nvp;
807     uint64_t phys_addr;
808     MemTxResult result;
809 
810     hw_cam = xive2_tctx_hw_cam_line(xptr, tctx);
811     nvp_blk = xive2_nvp_blk(hw_cam);
812     nvp_idx = xive2_nvp_idx(hw_cam);
813 
814     if (xive2_router_get_nvp(xrtr, nvp_blk, nvp_idx, &nvp)) {
815         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: No NVP %x/%x\n",
816                       nvp_blk, nvp_idx);
817         return;
818     }
819 
820     if (!xive2_nvp_is_valid(&nvp)) {
821         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: invalid NVP %x/%x\n",
822                       nvp_blk, nvp_idx);
823         return;
824     }
825 
826     xive2_cfg = xive2_router_get_config(xrtr);
827 
828     phys_addr = xive2_nvp_reporting_addr(&nvp) + 0x80; /* odd line */
829     if (xive2_cfg & XIVE2_GEN1_TIMA_OS) {
830         uint8_t pull_ctxt[REPORT_LINE_GEN1_SIZE];
831 
832         xive2_tm_report_line_gen1(tctx, pull_ctxt, REPORT_LINE_GEN1_SIZE);
833         result = dma_memory_write(&address_space_memory, phys_addr,
834                                   pull_ctxt, REPORT_LINE_GEN1_SIZE,
835                                   MEMTXATTRS_UNSPECIFIED);
836         assert(result == MEMTX_OK);
837     } else {
838         result = dma_memory_write(&address_space_memory, phys_addr,
839                                   &tctx->regs, sizeof(tctx->regs),
840                                   MEMTXATTRS_UNSPECIFIED);
841         assert(result == MEMTX_OK);
842         reserved = 0xFFFFFFFF;
843         result = dma_memory_write(&address_space_memory, phys_addr + 12,
844                                   &reserved, sizeof(reserved),
845                                   MEMTXATTRS_UNSPECIFIED);
846         assert(result == MEMTX_OK);
847     }
848 
849     /* the rest is similar to pull context to registers */
850     xive2_tm_pull_ctx(xptr, tctx, offset, size, ring);
851 }
852 
853 void xive2_tm_pull_os_ctx_ol(XivePresenter *xptr, XiveTCTX *tctx,
854                              hwaddr offset, uint64_t value, unsigned size)
855 {
856     xive2_tm_pull_ctx_ol(xptr, tctx, offset, value, size, TM_QW1_OS);
857 }
858 
859 
860 void xive2_tm_pull_phys_ctx_ol(XivePresenter *xptr, XiveTCTX *tctx,
861                                hwaddr offset, uint64_t value, unsigned size)
862 {
863     xive2_tm_pull_ctx_ol(xptr, tctx, offset, value, size, TM_QW3_HV_PHYS);
864 }
865 
866 static uint8_t xive2_tctx_restore_os_ctx(Xive2Router *xrtr, XiveTCTX *tctx,
867                                         uint8_t nvp_blk, uint32_t nvp_idx,
868                                         Xive2Nvp *nvp)
869 {
870     CPUPPCState *env = &POWERPC_CPU(tctx->cs)->env;
871     uint32_t pir = env->spr_cb[SPR_PIR].default_value;
872     uint8_t cppr;
873 
874     if (!xive2_nvp_is_hw(nvp)) {
875         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: NVP %x/%x is not HW owned\n",
876                       nvp_blk, nvp_idx);
877         return 0;
878     }
879 
880     cppr = xive_get_field32(NVP2_W2_CPPR, nvp->w2);
881     nvp->w2 = xive_set_field32(NVP2_W2_CPPR, nvp->w2, 0);
882     xive2_router_write_nvp(xrtr, nvp_blk, nvp_idx, nvp, 2);
883 
884     tctx->regs[TM_QW1_OS + TM_CPPR] = cppr;
885     tctx->regs[TM_QW1_OS + TM_LSMFB] = xive_get_field32(NVP2_W2_LSMFB, nvp->w2);
886     tctx->regs[TM_QW1_OS + TM_LGS] = xive_get_field32(NVP2_W2_LGS, nvp->w2);
887     tctx->regs[TM_QW1_OS + TM_T] = xive_get_field32(NVP2_W2_T, nvp->w2);
888 
889     nvp->w1 = xive_set_field32(NVP2_W1_CO, nvp->w1, 1);
890     nvp->w1 = xive_set_field32(NVP2_W1_CO_THRID_VALID, nvp->w1, 1);
891     nvp->w1 = xive_set_field32(NVP2_W1_CO_THRID, nvp->w1, pir);
892 
893     /*
894      * Checkout privilege: 0:OS, 1:Pool, 2:Hard
895      *
896      * TODO: we only support OS push/pull
897      */
898     nvp->w1 = xive_set_field32(NVP2_W1_CO_PRIV, nvp->w1, 0);
899 
900     xive2_router_write_nvp(xrtr, nvp_blk, nvp_idx, nvp, 1);
901 
902     /* return restored CPPR to generate a CPU exception if needed */
903     return cppr;
904 }
905 
906 static void xive2_tctx_process_pending(XiveTCTX *tctx, uint8_t sig_ring);
907 
908 static void xive2_tctx_need_resend(Xive2Router *xrtr, XiveTCTX *tctx,
909                                    uint8_t nvp_blk, uint32_t nvp_idx,
910                                    bool do_restore)
911 {
912     uint8_t *regs = &tctx->regs[TM_QW1_OS];
913     uint8_t ipb;
914     Xive2Nvp nvp;
915 
916     /*
917      * Grab the associated thread interrupt context registers in the
918      * associated NVP
919      */
920     if (xive2_router_get_nvp(xrtr, nvp_blk, nvp_idx, &nvp)) {
921         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: No NVP %x/%x\n",
922                       nvp_blk, nvp_idx);
923         return;
924     }
925 
926     if (!xive2_nvp_is_valid(&nvp)) {
927         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: invalid NVP %x/%x\n",
928                       nvp_blk, nvp_idx);
929         return;
930     }
931 
932     /* Automatically restore thread context registers */
933     if (xive2_router_get_config(xrtr) & XIVE2_VP_SAVE_RESTORE &&
934         do_restore) {
935         xive2_tctx_restore_os_ctx(xrtr, tctx, nvp_blk, nvp_idx, &nvp);
936     }
937 
938     ipb = xive_get_field32(NVP2_W2_IPB, nvp.w2);
939     if (ipb) {
940         nvp.w2 = xive_set_field32(NVP2_W2_IPB, nvp.w2, 0);
941         xive2_router_write_nvp(xrtr, nvp_blk, nvp_idx, &nvp, 2);
942     }
943     /* IPB bits in the backlog are merged with the TIMA IPB bits */
944     regs[TM_IPB] |= ipb;
945 
946     xive2_tctx_process_pending(tctx, TM_QW1_OS);
947 }
948 
949 /*
950  * Updating the OS CAM line can trigger a resend of interrupt
951  */
952 void xive2_tm_push_os_ctx(XivePresenter *xptr, XiveTCTX *tctx,
953                           hwaddr offset, uint64_t value, unsigned size)
954 {
955     uint32_t cam;
956     uint32_t qw1w2;
957     uint64_t qw1dw1;
958     uint8_t nvp_blk;
959     uint32_t nvp_idx;
960     bool vo;
961     bool do_restore;
962 
963     /* First update the thead context */
964     switch (size) {
965     case 4:
966         cam = value;
967         qw1w2 = cpu_to_be32(cam);
968         memcpy(&tctx->regs[TM_QW1_OS + TM_WORD2], &qw1w2, 4);
969         break;
970     case 8:
971         cam = value >> 32;
972         qw1dw1 = cpu_to_be64(value);
973         memcpy(&tctx->regs[TM_QW1_OS + TM_WORD2], &qw1dw1, 8);
974         break;
975     default:
976         g_assert_not_reached();
977     }
978 
979     xive2_cam_decode(cam, &nvp_blk, &nvp_idx, &vo, &do_restore);
980 
981     /* Check the interrupt pending bits */
982     if (vo) {
983         xive2_tctx_need_resend(XIVE2_ROUTER(xptr), tctx, nvp_blk, nvp_idx,
984                                do_restore);
985     }
986 }
987 
988 /* returns -1 if ring is invalid, but still populates block and index */
989 static int xive2_tctx_get_nvp_indexes(XiveTCTX *tctx, uint8_t ring,
990                                       uint8_t *nvp_blk, uint32_t *nvp_idx)
991 {
992     uint32_t w2;
993     uint32_t cam = 0;
994     int rc = 0;
995 
996     w2 = xive_tctx_word2(&tctx->regs[ring]);
997     switch (ring) {
998     case TM_QW1_OS:
999         if (!(be32_to_cpu(w2) & TM2_QW1W2_VO)) {
1000             rc = -1;
1001         }
1002         cam = xive_get_field32(TM2_QW1W2_OS_CAM, w2);
1003         break;
1004     case TM_QW2_HV_POOL:
1005         if (!(be32_to_cpu(w2) & TM2_QW2W2_VP)) {
1006             rc = -1;
1007         }
1008         cam = xive_get_field32(TM2_QW2W2_POOL_CAM, w2);
1009         break;
1010     case TM_QW3_HV_PHYS:
1011         if (!(be32_to_cpu(w2) & TM2_QW3W2_VT)) {
1012             rc = -1;
1013         }
1014         cam = xive2_tctx_hw_cam_line(tctx->xptr, tctx);
1015         break;
1016     default:
1017         rc = -1;
1018     }
1019     *nvp_blk = xive2_nvp_blk(cam);
1020     *nvp_idx = xive2_nvp_idx(cam);
1021     return rc;
1022 }
1023 
1024 static void xive2_tctx_accept_el(XivePresenter *xptr, XiveTCTX *tctx,
1025                                  uint8_t ring, uint8_t cl_ring)
1026 {
1027     uint64_t rd;
1028     Xive2Router *xrtr = XIVE2_ROUTER(xptr);
1029     uint32_t nvp_idx, xive2_cfg;
1030     uint8_t nvp_blk;
1031     Xive2Nvp nvp;
1032     uint64_t phys_addr;
1033     uint8_t OGen = 0;
1034 
1035     xive2_tctx_get_nvp_indexes(tctx, cl_ring, &nvp_blk, &nvp_idx);
1036 
1037     if (xive2_router_get_nvp(xrtr, (uint8_t)nvp_blk, nvp_idx, &nvp)) {
1038         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: No NVP %x/%x\n",
1039                       nvp_blk, nvp_idx);
1040         return;
1041     }
1042 
1043     if (!xive2_nvp_is_valid(&nvp)) {
1044         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: invalid NVP %x/%x\n",
1045                       nvp_blk, nvp_idx);
1046         return;
1047     }
1048 
1049 
1050     rd = xive_tctx_accept(tctx, ring);
1051 
1052     if (ring == TM_QW1_OS) {
1053         OGen = tctx->regs[ring + TM_OGEN];
1054     }
1055     xive2_cfg = xive2_router_get_config(xrtr);
1056     phys_addr = xive2_nvp_reporting_addr(&nvp);
1057     uint8_t report_data[REPORT_LINE_GEN1_SIZE];
1058     memset(report_data, 0xff, sizeof(report_data));
1059     if ((OGen == 1) || (xive2_cfg & XIVE2_GEN1_TIMA_OS)) {
1060         report_data[8] = (rd >> 8) & 0xff;
1061         report_data[9] = rd & 0xff;
1062     } else {
1063         report_data[0] = (rd >> 8) & 0xff;
1064         report_data[1] = rd & 0xff;
1065     }
1066     cpu_physical_memory_write(phys_addr, report_data, REPORT_LINE_GEN1_SIZE);
1067 }
1068 
1069 void xive2_tm_ack_os_el(XivePresenter *xptr, XiveTCTX *tctx,
1070                         hwaddr offset, uint64_t value, unsigned size)
1071 {
1072     xive2_tctx_accept_el(xptr, tctx, TM_QW1_OS, TM_QW1_OS);
1073 }
1074 
1075 /* Re-calculate and present pending interrupts */
1076 static void xive2_tctx_process_pending(XiveTCTX *tctx, uint8_t sig_ring)
1077 {
1078     uint8_t *sig_regs = &tctx->regs[sig_ring];
1079     Xive2Router *xrtr = XIVE2_ROUTER(tctx->xptr);
1080     uint8_t backlog_prio;
1081     uint8_t first_group;
1082     uint8_t group_level;
1083     uint8_t pipr_min;
1084     uint8_t lsmfb_min;
1085     uint8_t ring_min;
1086     uint8_t cppr = sig_regs[TM_CPPR];
1087     bool group_enabled;
1088     Xive2Nvp nvp;
1089     int rc;
1090 
1091     g_assert(sig_ring == TM_QW3_HV_PHYS || sig_ring == TM_QW1_OS);
1092 
1093     /*
1094      * Recompute the PIPR based on local pending interrupts. It will
1095      * be adjusted below if needed in case of pending group interrupts.
1096      */
1097 again:
1098     pipr_min = xive_ipb_to_pipr(sig_regs[TM_IPB]);
1099     group_enabled = !!sig_regs[TM_LGS];
1100     lsmfb_min = group_enabled ? sig_regs[TM_LSMFB] : 0xff;
1101     ring_min = sig_ring;
1102     group_level = 0;
1103 
1104     /* PHYS updates also depend on POOL values */
1105     if (sig_ring == TM_QW3_HV_PHYS) {
1106         uint8_t *pool_regs = &tctx->regs[TM_QW2_HV_POOL];
1107 
1108         /* POOL values only matter if POOL ctx is valid */
1109         if (pool_regs[TM_WORD2] & 0x80) {
1110             uint8_t pool_pipr = xive_ipb_to_pipr(pool_regs[TM_IPB]);
1111             uint8_t pool_lsmfb = pool_regs[TM_LSMFB];
1112 
1113             /*
1114              * Determine highest priority interrupt and
1115              * remember which ring has it.
1116              */
1117             if (pool_pipr < pipr_min) {
1118                 pipr_min = pool_pipr;
1119                 if (pool_pipr < lsmfb_min) {
1120                     ring_min = TM_QW2_HV_POOL;
1121                 }
1122             }
1123 
1124             /* Values needed for group priority calculation */
1125             if (pool_regs[TM_LGS] && (pool_lsmfb < lsmfb_min)) {
1126                 group_enabled = true;
1127                 lsmfb_min = pool_lsmfb;
1128                 if (lsmfb_min < pipr_min) {
1129                     ring_min = TM_QW2_HV_POOL;
1130                 }
1131             }
1132         }
1133     }
1134 
1135     if (group_enabled &&
1136         lsmfb_min < cppr &&
1137         lsmfb_min < pipr_min) {
1138 
1139         uint8_t nvp_blk;
1140         uint32_t nvp_idx;
1141 
1142         /*
1143          * Thread has seen a group interrupt with a higher priority
1144          * than the new cppr or pending local interrupt. Check the
1145          * backlog
1146          */
1147         rc = xive2_tctx_get_nvp_indexes(tctx, ring_min, &nvp_blk, &nvp_idx);
1148         if (rc) {
1149             qemu_log_mask(LOG_GUEST_ERROR, "XIVE: set CPPR on invalid "
1150                                            "context\n");
1151             return;
1152         }
1153 
1154         if (xive2_router_get_nvp(xrtr, nvp_blk, nvp_idx, &nvp)) {
1155             qemu_log_mask(LOG_GUEST_ERROR, "XIVE: No NVP %x/%x\n",
1156                           nvp_blk, nvp_idx);
1157             return;
1158         }
1159 
1160         if (!xive2_nvp_is_valid(&nvp)) {
1161             qemu_log_mask(LOG_GUEST_ERROR, "XIVE: invalid NVP %x/%x\n",
1162                           nvp_blk, nvp_idx);
1163             return;
1164         }
1165 
1166         first_group = xive_get_field32(NVP2_W0_PGOFIRST, nvp.w0);
1167         if (!first_group) {
1168             qemu_log_mask(LOG_GUEST_ERROR, "XIVE: invalid NVP %x/%x\n",
1169                           nvp_blk, nvp_idx);
1170             return;
1171         }
1172 
1173         backlog_prio = xive2_presenter_backlog_scan(tctx->xptr,
1174                                                     nvp_blk, nvp_idx,
1175                                                     first_group, &group_level);
1176         tctx->regs[ring_min + TM_LSMFB] = backlog_prio;
1177         if (backlog_prio != lsmfb_min) {
1178             /*
1179              * If the group backlog scan finds a less favored or no interrupt,
1180              * then re-do the processing which may turn up a more favored
1181              * interrupt from IPB or the other pool. Backlog should not
1182              * find a priority < LSMFB.
1183              */
1184             g_assert(backlog_prio >= lsmfb_min);
1185             goto again;
1186         }
1187 
1188         xive2_presenter_backlog_decr(tctx->xptr, nvp_blk, nvp_idx,
1189                                      backlog_prio, group_level);
1190         pipr_min = backlog_prio;
1191     }
1192 
1193     if (pipr_min > cppr) {
1194         pipr_min = cppr;
1195     }
1196     xive_tctx_pipr_set(tctx, ring_min, pipr_min, group_level);
1197 }
1198 
1199 /* NOTE: CPPR only exists for TM_QW1_OS and TM_QW3_HV_PHYS */
1200 static void xive2_tctx_set_cppr(XiveTCTX *tctx, uint8_t sig_ring, uint8_t cppr)
1201 {
1202     uint8_t *sig_regs = &tctx->regs[sig_ring];
1203     Xive2Router *xrtr = XIVE2_ROUTER(tctx->xptr);
1204     uint8_t old_cppr;
1205     uint8_t nsr = sig_regs[TM_NSR];
1206 
1207     g_assert(sig_ring == TM_QW1_OS || sig_ring == TM_QW3_HV_PHYS);
1208 
1209     g_assert(tctx->regs[TM_QW2_HV_POOL + TM_NSR] == 0);
1210     g_assert(tctx->regs[TM_QW2_HV_POOL + TM_PIPR] == 0);
1211     g_assert(tctx->regs[TM_QW2_HV_POOL + TM_CPPR] == 0);
1212 
1213     /* XXX: should show pool IPB for PHYS ring */
1214     trace_xive_tctx_set_cppr(tctx->cs->cpu_index, sig_ring,
1215                              sig_regs[TM_IPB], sig_regs[TM_PIPR],
1216                              cppr, nsr);
1217 
1218     if (cppr > XIVE_PRIORITY_MAX) {
1219         cppr = 0xff;
1220     }
1221 
1222     old_cppr = sig_regs[TM_CPPR];
1223     sig_regs[TM_CPPR] = cppr;
1224 
1225     /* Handle increased CPPR priority (lower value) */
1226     if (cppr < old_cppr) {
1227         if (cppr <= sig_regs[TM_PIPR]) {
1228             /* CPPR lowered below PIPR, must un-present interrupt */
1229             if (xive_nsr_indicates_exception(sig_ring, nsr)) {
1230                 if (xive_nsr_indicates_group_exception(sig_ring, nsr)) {
1231                     /* redistribute precluded active grp interrupt */
1232                     xive2_redistribute(xrtr, tctx,
1233                                        xive_nsr_exception_ring(sig_ring, nsr));
1234                     return;
1235                 }
1236             }
1237 
1238             /* interrupt is VP directed, pending in IPB */
1239             xive_tctx_pipr_set(tctx, sig_ring, cppr, 0);
1240             return;
1241         } else {
1242             /* CPPR was lowered, but still above PIPR. No action needed. */
1243             return;
1244         }
1245     }
1246 
1247     /* CPPR didn't change, nothing needs to be done */
1248     if (cppr == old_cppr) {
1249         return;
1250     }
1251 
1252     /* CPPR priority decreased (higher value) */
1253     if (!xive_nsr_indicates_exception(sig_ring, nsr)) {
1254         xive2_tctx_process_pending(tctx, sig_ring);
1255     }
1256 }
1257 
1258 void xive2_tm_set_hv_cppr(XivePresenter *xptr, XiveTCTX *tctx,
1259                           hwaddr offset, uint64_t value, unsigned size)
1260 {
1261     xive2_tctx_set_cppr(tctx, TM_QW3_HV_PHYS, value & 0xff);
1262 }
1263 
1264 void xive2_tm_set_os_cppr(XivePresenter *xptr, XiveTCTX *tctx,
1265                           hwaddr offset, uint64_t value, unsigned size)
1266 {
1267     xive2_tctx_set_cppr(tctx, TM_QW1_OS, value & 0xff);
1268 }
1269 
1270 static void xive2_tctx_set_target(XiveTCTX *tctx, uint8_t ring, uint8_t target)
1271 {
1272     uint8_t *regs = &tctx->regs[ring];
1273 
1274     regs[TM_T] = target;
1275 }
1276 
1277 void xive2_tm_set_hv_target(XivePresenter *xptr, XiveTCTX *tctx,
1278                             hwaddr offset, uint64_t value, unsigned size)
1279 {
1280     xive2_tctx_set_target(tctx, TM_QW3_HV_PHYS, value & 0xff);
1281 }
1282 
1283 /*
1284  * XIVE Router (aka. Virtualization Controller or IVRE)
1285  */
1286 
1287 int xive2_router_get_eas(Xive2Router *xrtr, uint8_t eas_blk, uint32_t eas_idx,
1288                          Xive2Eas *eas)
1289 {
1290     Xive2RouterClass *xrc = XIVE2_ROUTER_GET_CLASS(xrtr);
1291 
1292     return xrc->get_eas(xrtr, eas_blk, eas_idx, eas);
1293 }
1294 
1295 static
1296 int xive2_router_get_pq(Xive2Router *xrtr, uint8_t eas_blk, uint32_t eas_idx,
1297                        uint8_t *pq)
1298 {
1299     Xive2RouterClass *xrc = XIVE2_ROUTER_GET_CLASS(xrtr);
1300 
1301     return xrc->get_pq(xrtr, eas_blk, eas_idx, pq);
1302 }
1303 
1304 static
1305 int xive2_router_set_pq(Xive2Router *xrtr, uint8_t eas_blk, uint32_t eas_idx,
1306                        uint8_t *pq)
1307 {
1308     Xive2RouterClass *xrc = XIVE2_ROUTER_GET_CLASS(xrtr);
1309 
1310     return xrc->set_pq(xrtr, eas_blk, eas_idx, pq);
1311 }
1312 
1313 int xive2_router_get_end(Xive2Router *xrtr, uint8_t end_blk, uint32_t end_idx,
1314                          Xive2End *end)
1315 {
1316    Xive2RouterClass *xrc = XIVE2_ROUTER_GET_CLASS(xrtr);
1317 
1318    return xrc->get_end(xrtr, end_blk, end_idx, end);
1319 }
1320 
1321 int xive2_router_write_end(Xive2Router *xrtr, uint8_t end_blk, uint32_t end_idx,
1322                            Xive2End *end, uint8_t word_number)
1323 {
1324    Xive2RouterClass *xrc = XIVE2_ROUTER_GET_CLASS(xrtr);
1325 
1326    return xrc->write_end(xrtr, end_blk, end_idx, end, word_number);
1327 }
1328 
1329 int xive2_router_get_nvp(Xive2Router *xrtr, uint8_t nvp_blk, uint32_t nvp_idx,
1330                          Xive2Nvp *nvp)
1331 {
1332    Xive2RouterClass *xrc = XIVE2_ROUTER_GET_CLASS(xrtr);
1333 
1334    return xrc->get_nvp(xrtr, nvp_blk, nvp_idx, nvp);
1335 }
1336 
1337 int xive2_router_write_nvp(Xive2Router *xrtr, uint8_t nvp_blk, uint32_t nvp_idx,
1338                            Xive2Nvp *nvp, uint8_t word_number)
1339 {
1340    Xive2RouterClass *xrc = XIVE2_ROUTER_GET_CLASS(xrtr);
1341 
1342    return xrc->write_nvp(xrtr, nvp_blk, nvp_idx, nvp, word_number);
1343 }
1344 
1345 int xive2_router_get_nvgc(Xive2Router *xrtr, bool crowd,
1346                           uint8_t nvgc_blk, uint32_t nvgc_idx,
1347                           Xive2Nvgc *nvgc)
1348 {
1349    Xive2RouterClass *xrc = XIVE2_ROUTER_GET_CLASS(xrtr);
1350 
1351    return xrc->get_nvgc(xrtr, crowd, nvgc_blk, nvgc_idx, nvgc);
1352 }
1353 
1354 int xive2_router_write_nvgc(Xive2Router *xrtr, bool crowd,
1355                             uint8_t nvgc_blk, uint32_t nvgc_idx,
1356                             Xive2Nvgc *nvgc)
1357 {
1358    Xive2RouterClass *xrc = XIVE2_ROUTER_GET_CLASS(xrtr);
1359 
1360    return xrc->write_nvgc(xrtr, crowd, nvgc_blk, nvgc_idx, nvgc);
1361 }
1362 
1363 static bool xive2_vp_match_mask(uint32_t cam1, uint32_t cam2,
1364                                 uint32_t vp_mask)
1365 {
1366     return (cam1 & vp_mask) == (cam2 & vp_mask);
1367 }
1368 
1369 static uint8_t xive2_get_vp_block_mask(uint32_t nvt_blk, bool crowd)
1370 {
1371     uint8_t block_mask = 0b1111;
1372 
1373     /* 3 supported crowd sizes: 2, 4, 16 */
1374     if (crowd) {
1375         uint32_t size = xive_get_vpgroup_size(nvt_blk);
1376 
1377         if (size != 2 && size != 4 && size != 16) {
1378             qemu_log_mask(LOG_GUEST_ERROR, "XIVE: Invalid crowd size of %d",
1379                                            size);
1380             return block_mask;
1381         }
1382         block_mask &= ~(size - 1);
1383     }
1384     return block_mask;
1385 }
1386 
1387 static uint32_t xive2_get_vp_index_mask(uint32_t nvt_index, bool cam_ignore)
1388 {
1389     uint32_t index_mask = 0xFFFFFF; /* 24 bits */
1390 
1391     if (cam_ignore) {
1392         uint32_t size = xive_get_vpgroup_size(nvt_index);
1393 
1394         if (size < 2) {
1395             qemu_log_mask(LOG_GUEST_ERROR, "XIVE: Invalid group size of %d",
1396                                            size);
1397             return index_mask;
1398         }
1399         index_mask &= ~(size - 1);
1400     }
1401     return index_mask;
1402 }
1403 
1404 /*
1405  * The thread context register words are in big-endian format.
1406  */
1407 int xive2_presenter_tctx_match(XivePresenter *xptr, XiveTCTX *tctx,
1408                                uint8_t format,
1409                                uint8_t nvt_blk, uint32_t nvt_idx,
1410                                bool crowd, bool cam_ignore,
1411                                uint32_t logic_serv)
1412 {
1413     uint32_t cam =   xive2_nvp_cam_line(nvt_blk, nvt_idx);
1414     uint32_t qw3w2 = xive_tctx_word2(&tctx->regs[TM_QW3_HV_PHYS]);
1415     uint32_t qw2w2 = xive_tctx_word2(&tctx->regs[TM_QW2_HV_POOL]);
1416     uint32_t qw1w2 = xive_tctx_word2(&tctx->regs[TM_QW1_OS]);
1417     uint32_t qw0w2 = xive_tctx_word2(&tctx->regs[TM_QW0_USER]);
1418 
1419     uint32_t index_mask, vp_mask;
1420     uint8_t block_mask;
1421 
1422     if (format == 0) {
1423         /*
1424          * i=0: Specific NVT notification
1425          * i=1: VP-group notification (bits ignored at the end of the
1426          *      NVT identifier)
1427          */
1428         block_mask = xive2_get_vp_block_mask(nvt_blk, crowd);
1429         index_mask = xive2_get_vp_index_mask(nvt_idx, cam_ignore);
1430         vp_mask = xive2_nvp_cam_line(block_mask, index_mask);
1431 
1432         /* For VP-group notifications, threads with LGS=0 are excluded */
1433 
1434         /* PHYS ring */
1435         if ((be32_to_cpu(qw3w2) & TM2_QW3W2_VT) &&
1436             !(cam_ignore && tctx->regs[TM_QW3_HV_PHYS + TM_LGS] == 0) &&
1437             xive2_vp_match_mask(cam,
1438                                 xive2_tctx_hw_cam_line(xptr, tctx),
1439                                 vp_mask)) {
1440             return TM_QW3_HV_PHYS;
1441         }
1442 
1443         /* HV POOL ring */
1444         if ((be32_to_cpu(qw2w2) & TM2_QW2W2_VP) &&
1445             !(cam_ignore && tctx->regs[TM_QW2_HV_POOL + TM_LGS] == 0) &&
1446             xive2_vp_match_mask(cam,
1447                                 xive_get_field32(TM2_QW2W2_POOL_CAM, qw2w2),
1448                                 vp_mask)) {
1449             return TM_QW2_HV_POOL;
1450         }
1451 
1452         /* OS ring */
1453         if ((be32_to_cpu(qw1w2) & TM2_QW1W2_VO) &&
1454             !(cam_ignore && tctx->regs[TM_QW1_OS + TM_LGS] == 0) &&
1455             xive2_vp_match_mask(cam,
1456                                 xive_get_field32(TM2_QW1W2_OS_CAM, qw1w2),
1457                                 vp_mask)) {
1458             return TM_QW1_OS;
1459         }
1460     } else {
1461         /* F=1 : User level Event-Based Branch (EBB) notification */
1462 
1463         /* FIXME: what if cam_ignore and LGS = 0 ? */
1464         /* USER ring */
1465         if  ((be32_to_cpu(qw1w2) & TM2_QW1W2_VO) &&
1466              (cam == xive_get_field32(TM2_QW1W2_OS_CAM, qw1w2)) &&
1467              (be32_to_cpu(qw0w2) & TM2_QW0W2_VU) &&
1468              (logic_serv == xive_get_field32(TM2_QW0W2_LOGIC_SERV, qw0w2))) {
1469             return TM_QW0_USER;
1470         }
1471     }
1472     return -1;
1473 }
1474 
1475 bool xive2_tm_irq_precluded(XiveTCTX *tctx, int ring, uint8_t priority)
1476 {
1477     uint8_t *sig_regs = xive_tctx_signal_regs(tctx, ring);
1478 
1479     /*
1480      * The xive2_presenter_tctx_match() above tells if there's a match
1481      * but for VP-group notification, we still need to look at the
1482      * priority to know if the thread can take the interrupt now or if
1483      * it is precluded.
1484      */
1485     if (priority < sig_regs[TM_PIPR]) {
1486         return false;
1487     }
1488     return true;
1489 }
1490 
1491 void xive2_tm_set_lsmfb(XiveTCTX *tctx, int ring, uint8_t priority)
1492 {
1493     uint8_t *regs = &tctx->regs[ring];
1494 
1495     /*
1496      * Called by the router during a VP-group notification when the
1497      * thread matches but can't take the interrupt because it's
1498      * already running at a more favored priority. It then stores the
1499      * new interrupt priority in the LSMFB field.
1500      */
1501     regs[TM_LSMFB] = priority;
1502 }
1503 
1504 static void xive2_router_realize(DeviceState *dev, Error **errp)
1505 {
1506     Xive2Router *xrtr = XIVE2_ROUTER(dev);
1507 
1508     assert(xrtr->xfb);
1509 }
1510 
1511 /*
1512  * Notification using the END ESe/ESn bit (Event State Buffer for
1513  * escalation and notification). Profide further coalescing in the
1514  * Router.
1515  */
1516 static bool xive2_router_end_es_notify(Xive2Router *xrtr, uint8_t end_blk,
1517                                        uint32_t end_idx, Xive2End *end,
1518                                        uint32_t end_esmask)
1519 {
1520     uint8_t pq = xive_get_field32(end_esmask, end->w1);
1521     bool notify = xive_esb_trigger(&pq);
1522 
1523     if (pq != xive_get_field32(end_esmask, end->w1)) {
1524         end->w1 = xive_set_field32(end_esmask, end->w1, pq);
1525         xive2_router_write_end(xrtr, end_blk, end_idx, end, 1);
1526     }
1527 
1528     /* ESe/n[Q]=1 : end of notification */
1529     return notify;
1530 }
1531 
1532 /*
1533  * An END trigger can come from an event trigger (IPI or HW) or from
1534  * another chip. We don't model the PowerBus but the END trigger
1535  * message has the same parameters than in the function below.
1536  */
1537 static void xive2_router_end_notify(Xive2Router *xrtr, uint8_t end_blk,
1538                                     uint32_t end_idx, uint32_t end_data,
1539                                     bool redistribute)
1540 {
1541     Xive2End end;
1542     uint8_t priority;
1543     uint8_t format;
1544     XiveTCTXMatch match;
1545     bool crowd, cam_ignore;
1546     uint8_t nvx_blk;
1547     uint32_t nvx_idx;
1548 
1549     /* END cache lookup */
1550     if (xive2_router_get_end(xrtr, end_blk, end_idx, &end)) {
1551         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: No END %x/%x\n", end_blk,
1552                       end_idx);
1553         return;
1554     }
1555 
1556     if (!xive2_end_is_valid(&end)) {
1557         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: END %x/%x is invalid\n",
1558                       end_blk, end_idx);
1559         return;
1560     }
1561 
1562     if (xive2_end_is_crowd(&end) && !xive2_end_is_ignore(&end)) {
1563         qemu_log_mask(LOG_GUEST_ERROR,
1564                       "XIVE: invalid END, 'crowd' bit requires 'ignore' bit\n");
1565         return;
1566     }
1567 
1568     if (!redistribute && xive2_end_is_enqueue(&end)) {
1569         trace_xive_end_enqueue(end_blk, end_idx, end_data);
1570         xive2_end_enqueue(&end, end_data);
1571         /* Enqueuing event data modifies the EQ toggle and index */
1572         xive2_router_write_end(xrtr, end_blk, end_idx, &end, 1);
1573     }
1574 
1575     /*
1576      * When the END is silent, we skip the notification part.
1577      */
1578     if (xive2_end_is_silent_escalation(&end)) {
1579         goto do_escalation;
1580     }
1581 
1582     /*
1583      * The W7 format depends on the F bit in W6. It defines the type
1584      * of the notification :
1585      *
1586      *   F=0 : single or multiple NVP notification
1587      *   F=1 : User level Event-Based Branch (EBB) notification, no
1588      *         priority
1589      */
1590     format = xive_get_field32(END2_W6_FORMAT_BIT, end.w6);
1591     priority = xive_get_field32(END2_W7_F0_PRIORITY, end.w7);
1592 
1593     /* The END is masked */
1594     if (format == 0 && priority == 0xff) {
1595         return;
1596     }
1597 
1598     /*
1599      * Check the END ESn (Event State Buffer for notification) for
1600      * even further coalescing in the Router
1601      */
1602     if (!xive2_end_is_notify(&end)) {
1603         /* ESn[Q]=1 : end of notification */
1604         if (!xive2_router_end_es_notify(xrtr, end_blk, end_idx,
1605                                        &end, END2_W1_ESn)) {
1606             return;
1607         }
1608     }
1609 
1610     /*
1611      * Follows IVPE notification
1612      */
1613     nvx_blk = xive_get_field32(END2_W6_VP_BLOCK, end.w6);
1614     nvx_idx = xive_get_field32(END2_W6_VP_OFFSET, end.w6);
1615     crowd = xive2_end_is_crowd(&end);
1616     cam_ignore = xive2_end_is_ignore(&end);
1617 
1618     /* TODO: Auto EOI. */
1619     if (xive_presenter_match(xrtr->xfb, format, nvx_blk, nvx_idx,
1620                              crowd, cam_ignore, priority,
1621                              xive_get_field32(END2_W7_F1_LOG_SERVER_ID, end.w7),
1622                              &match)) {
1623         XiveTCTX *tctx = match.tctx;
1624         uint8_t ring = match.ring;
1625         uint8_t *sig_regs = xive_tctx_signal_regs(tctx, ring);
1626         uint8_t nsr = sig_regs[TM_NSR];
1627         uint8_t group_level;
1628 
1629         if (priority < sig_regs[TM_PIPR] &&
1630             xive_nsr_indicates_group_exception(ring, nsr)) {
1631             xive2_redistribute(xrtr, tctx, xive_nsr_exception_ring(ring, nsr));
1632         }
1633 
1634         group_level = xive_get_group_level(crowd, cam_ignore, nvx_blk, nvx_idx);
1635         trace_xive_presenter_notify(nvx_blk, nvx_idx, ring, group_level);
1636         xive_tctx_pipr_present(tctx, ring, priority, group_level);
1637         return;
1638     }
1639 
1640     /*
1641      * If no matching NVP is dispatched on a HW thread :
1642      * - specific VP: update the NVP structure if backlog is activated
1643      * - VP-group: update the backlog counter for that priority in the NVG
1644      */
1645     if (xive2_end_is_backlog(&end)) {
1646 
1647         if (format == 1) {
1648             qemu_log_mask(LOG_GUEST_ERROR,
1649                           "XIVE: END %x/%x invalid config: F1 & backlog\n",
1650                           end_blk, end_idx);
1651             return;
1652         }
1653 
1654         if (!cam_ignore) {
1655             uint8_t ipb;
1656             Xive2Nvp nvp;
1657 
1658             /* NVP cache lookup */
1659             if (xive2_router_get_nvp(xrtr, nvx_blk, nvx_idx, &nvp)) {
1660                 qemu_log_mask(LOG_GUEST_ERROR, "XIVE: no NVP %x/%x\n",
1661                               nvx_blk, nvx_idx);
1662                 return;
1663             }
1664 
1665             if (!xive2_nvp_is_valid(&nvp)) {
1666                 qemu_log_mask(LOG_GUEST_ERROR, "XIVE: NVP %x/%x is invalid\n",
1667                               nvx_blk, nvx_idx);
1668                 return;
1669             }
1670 
1671             /*
1672              * Record the IPB in the associated NVP structure for later
1673              * use. The presenter will resend the interrupt when the vCPU
1674              * is dispatched again on a HW thread.
1675              */
1676             ipb = xive_get_field32(NVP2_W2_IPB, nvp.w2) |
1677                 xive_priority_to_ipb(priority);
1678             nvp.w2 = xive_set_field32(NVP2_W2_IPB, nvp.w2, ipb);
1679             xive2_router_write_nvp(xrtr, nvx_blk, nvx_idx, &nvp, 2);
1680         } else {
1681             Xive2Nvgc nvgc;
1682             uint32_t backlog;
1683 
1684             /*
1685              * For groups and crowds, the per-priority backlog
1686              * counters are stored in the NVG/NVC structures
1687              */
1688             if (xive2_router_get_nvgc(xrtr, crowd,
1689                                       nvx_blk, nvx_idx, &nvgc)) {
1690                 qemu_log_mask(LOG_GUEST_ERROR, "XIVE: no %s %x/%x\n",
1691                               crowd ? "NVC" : "NVG", nvx_blk, nvx_idx);
1692                 return;
1693             }
1694 
1695             if (!xive2_nvgc_is_valid(&nvgc)) {
1696                 qemu_log_mask(LOG_GUEST_ERROR, "XIVE: NVG %x/%x is invalid\n",
1697                               nvx_blk, nvx_idx);
1698                 return;
1699             }
1700 
1701             /*
1702              * Increment the backlog counter for that priority.
1703              * We only call broadcast the first time the counter is
1704              * incremented. broadcast will set the LSMFB field of the TIMA of
1705              * relevant threads so that they know an interrupt is pending.
1706              */
1707             backlog = xive2_nvgc_get_backlog(&nvgc, priority) + 1;
1708             xive2_nvgc_set_backlog(&nvgc, priority, backlog);
1709             xive2_router_write_nvgc(xrtr, crowd, nvx_blk, nvx_idx, &nvgc);
1710 
1711             if (backlog == 1) {
1712                 XiveFabricClass *xfc = XIVE_FABRIC_GET_CLASS(xrtr->xfb);
1713                 xfc->broadcast(xrtr->xfb, nvx_blk, nvx_idx,
1714                                crowd, cam_ignore, priority);
1715 
1716                 if (!xive2_end_is_precluded_escalation(&end)) {
1717                     /*
1718                      * The interrupt will be picked up when the
1719                      * matching thread lowers its priority level
1720                      */
1721                     return;
1722                 }
1723             }
1724         }
1725     }
1726 
1727 do_escalation:
1728     /*
1729      * If activated, escalate notification using the ESe PQ bits and
1730      * the EAS in w4-5
1731      */
1732     if (!xive2_end_is_escalate(&end)) {
1733         return;
1734     }
1735 
1736     /*
1737      * Check the END ESe (Event State Buffer for escalation) for even
1738      * further coalescing in the Router
1739      */
1740     if (!xive2_end_is_uncond_escalation(&end)) {
1741         /* ESe[Q]=1 : end of escalation notification */
1742         if (!xive2_router_end_es_notify(xrtr, end_blk, end_idx,
1743                                        &end, END2_W1_ESe)) {
1744             return;
1745         }
1746     }
1747 
1748     if (xive2_end_is_escalate_end(&end)) {
1749         /*
1750          * Perform END Adaptive escalation processing
1751          * The END trigger becomes an Escalation trigger
1752          */
1753         uint8_t esc_blk = xive_get_field32(END2_W4_END_BLOCK, end.w4);
1754         uint32_t esc_idx = xive_get_field32(END2_W4_ESC_END_INDEX, end.w4);
1755         uint32_t esc_data = xive_get_field32(END2_W5_ESC_END_DATA, end.w5);
1756         trace_xive_escalate_end(end_blk, end_idx, esc_blk, esc_idx, esc_data);
1757         xive2_router_end_notify(xrtr, esc_blk, esc_idx, esc_data, false);
1758     } /* end END adaptive escalation */
1759 
1760     else {
1761         uint32_t lisn;              /* Logical Interrupt Source Number */
1762 
1763         /*
1764          *  Perform ESB escalation processing
1765          *      E[N] == 1 --> N
1766          *      Req[Block] <- E[ESB_Block]
1767          *      Req[Index] <- E[ESB_Index]
1768          *      Req[Offset] <- 0x000
1769          *      Execute <ESB Store> Req command
1770          */
1771         lisn = XIVE_EAS(xive_get_field32(END2_W4_END_BLOCK,     end.w4),
1772                         xive_get_field32(END2_W4_ESC_END_INDEX, end.w4));
1773 
1774         trace_xive_escalate_esb(end_blk, end_idx, lisn);
1775         xive2_notify(xrtr, lisn, true /* pq_checked */);
1776     }
1777 
1778     return;
1779 }
1780 
1781 void xive2_notify(Xive2Router *xrtr , uint32_t lisn, bool pq_checked)
1782 {
1783     uint8_t eas_blk = XIVE_EAS_BLOCK(lisn);
1784     uint32_t eas_idx = XIVE_EAS_INDEX(lisn);
1785     Xive2Eas eas;
1786 
1787     /* EAS cache lookup */
1788     if (xive2_router_get_eas(xrtr, eas_blk, eas_idx, &eas)) {
1789         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: Unknown LISN %x\n", lisn);
1790         return;
1791     }
1792 
1793     if (!pq_checked) {
1794         bool notify;
1795         uint8_t pq;
1796 
1797         /* PQ cache lookup */
1798         if (xive2_router_get_pq(xrtr, eas_blk, eas_idx, &pq)) {
1799             /* Set FIR */
1800             g_assert_not_reached();
1801         }
1802 
1803         notify = xive_esb_trigger(&pq);
1804 
1805         if (xive2_router_set_pq(xrtr, eas_blk, eas_idx, &pq)) {
1806             /* Set FIR */
1807             g_assert_not_reached();
1808         }
1809 
1810         if (!notify) {
1811             return;
1812         }
1813     }
1814 
1815     if (!xive2_eas_is_valid(&eas)) {
1816         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: Invalid LISN %x\n", lisn);
1817         return;
1818     }
1819 
1820     if (xive2_eas_is_masked(&eas)) {
1821         /* Notification completed */
1822         return;
1823     }
1824 
1825     /* TODO: add support for EAS resume */
1826     if (xive2_eas_is_resume(&eas)) {
1827         qemu_log_mask(LOG_UNIMP,
1828                       "XIVE: EAS resume processing unimplemented - LISN %x\n",
1829                       lisn);
1830         return;
1831     }
1832 
1833     /*
1834      * The event trigger becomes an END trigger
1835      */
1836     xive2_router_end_notify(xrtr,
1837                             xive_get_field64(EAS2_END_BLOCK, eas.w),
1838                             xive_get_field64(EAS2_END_INDEX, eas.w),
1839                             xive_get_field64(EAS2_END_DATA,  eas.w),
1840                             false);
1841     return;
1842 }
1843 
1844 void xive2_router_notify(XiveNotifier *xn, uint32_t lisn, bool pq_checked)
1845 {
1846     Xive2Router *xrtr = XIVE2_ROUTER(xn);
1847 
1848     xive2_notify(xrtr, lisn, pq_checked);
1849     return;
1850 }
1851 
1852 static const Property xive2_router_properties[] = {
1853     DEFINE_PROP_LINK("xive-fabric", Xive2Router, xfb,
1854                      TYPE_XIVE_FABRIC, XiveFabric *),
1855 };
1856 
1857 static void xive2_router_class_init(ObjectClass *klass, const void *data)
1858 {
1859     DeviceClass *dc = DEVICE_CLASS(klass);
1860     XiveNotifierClass *xnc = XIVE_NOTIFIER_CLASS(klass);
1861 
1862     dc->desc    = "XIVE2 Router Engine";
1863     device_class_set_props(dc, xive2_router_properties);
1864     /* Parent is SysBusDeviceClass. No need to call its realize hook */
1865     dc->realize = xive2_router_realize;
1866     xnc->notify = xive2_router_notify;
1867 }
1868 
1869 static const TypeInfo xive2_router_info = {
1870     .name          = TYPE_XIVE2_ROUTER,
1871     .parent        = TYPE_SYS_BUS_DEVICE,
1872     .abstract      = true,
1873     .instance_size = sizeof(Xive2Router),
1874     .class_size    = sizeof(Xive2RouterClass),
1875     .class_init    = xive2_router_class_init,
1876     .interfaces    = (const InterfaceInfo[]) {
1877         { TYPE_XIVE_NOTIFIER },
1878         { TYPE_XIVE_PRESENTER },
1879         { }
1880     }
1881 };
1882 
1883 static inline bool addr_is_even(hwaddr addr, uint32_t shift)
1884 {
1885     return !((addr >> shift) & 1);
1886 }
1887 
1888 static uint64_t xive2_end_source_read(void *opaque, hwaddr addr, unsigned size)
1889 {
1890     Xive2EndSource *xsrc = XIVE2_END_SOURCE(opaque);
1891     uint32_t offset = addr & 0xFFF;
1892     uint8_t end_blk;
1893     uint32_t end_idx;
1894     Xive2End end;
1895     uint32_t end_esmask;
1896     uint8_t pq;
1897     uint64_t ret;
1898 
1899     /*
1900      * The block id should be deduced from the load address on the END
1901      * ESB MMIO but our model only supports a single block per XIVE chip.
1902      */
1903     end_blk = xive2_router_get_block_id(xsrc->xrtr);
1904     end_idx = addr >> (xsrc->esb_shift + 1);
1905 
1906     if (xive2_router_get_end(xsrc->xrtr, end_blk, end_idx, &end)) {
1907         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: No END %x/%x\n", end_blk,
1908                       end_idx);
1909         return -1;
1910     }
1911 
1912     if (!xive2_end_is_valid(&end)) {
1913         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: END %x/%x is invalid\n",
1914                       end_blk, end_idx);
1915         return -1;
1916     }
1917 
1918     end_esmask = addr_is_even(addr, xsrc->esb_shift) ? END2_W1_ESn :
1919         END2_W1_ESe;
1920     pq = xive_get_field32(end_esmask, end.w1);
1921 
1922     switch (offset) {
1923     case XIVE_ESB_LOAD_EOI ... XIVE_ESB_LOAD_EOI + 0x7FF:
1924         ret = xive_esb_eoi(&pq);
1925 
1926         /* Forward the source event notification for routing ?? */
1927         break;
1928 
1929     case XIVE_ESB_GET ... XIVE_ESB_GET + 0x3FF:
1930         ret = pq;
1931         break;
1932 
1933     case XIVE_ESB_SET_PQ_00 ... XIVE_ESB_SET_PQ_00 + 0x0FF:
1934     case XIVE_ESB_SET_PQ_01 ... XIVE_ESB_SET_PQ_01 + 0x0FF:
1935     case XIVE_ESB_SET_PQ_10 ... XIVE_ESB_SET_PQ_10 + 0x0FF:
1936     case XIVE_ESB_SET_PQ_11 ... XIVE_ESB_SET_PQ_11 + 0x0FF:
1937         ret = xive_esb_set(&pq, (offset >> 8) & 0x3);
1938         break;
1939     default:
1940         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: invalid END ESB load addr %d\n",
1941                       offset);
1942         return -1;
1943     }
1944 
1945     if (pq != xive_get_field32(end_esmask, end.w1)) {
1946         end.w1 = xive_set_field32(end_esmask, end.w1, pq);
1947         xive2_router_write_end(xsrc->xrtr, end_blk, end_idx, &end, 1);
1948     }
1949 
1950     return ret;
1951 }
1952 
1953 static void xive2_end_source_write(void *opaque, hwaddr addr,
1954                                    uint64_t value, unsigned size)
1955 {
1956     Xive2EndSource *xsrc = XIVE2_END_SOURCE(opaque);
1957     uint32_t offset = addr & 0xFFF;
1958     uint8_t end_blk;
1959     uint32_t end_idx;
1960     Xive2End end;
1961     uint32_t end_esmask;
1962     uint8_t pq;
1963     bool notify = false;
1964 
1965     /*
1966      * The block id should be deduced from the load address on the END
1967      * ESB MMIO but our model only supports a single block per XIVE chip.
1968      */
1969     end_blk = xive2_router_get_block_id(xsrc->xrtr);
1970     end_idx = addr >> (xsrc->esb_shift + 1);
1971 
1972     if (xive2_router_get_end(xsrc->xrtr, end_blk, end_idx, &end)) {
1973         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: No END %x/%x\n", end_blk,
1974                       end_idx);
1975         return;
1976     }
1977 
1978     if (!xive2_end_is_valid(&end)) {
1979         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: END %x/%x is invalid\n",
1980                       end_blk, end_idx);
1981         return;
1982     }
1983 
1984     end_esmask = addr_is_even(addr, xsrc->esb_shift) ? END2_W1_ESn :
1985         END2_W1_ESe;
1986     pq = xive_get_field32(end_esmask, end.w1);
1987 
1988     switch (offset) {
1989     case 0 ... 0x3FF:
1990         notify = xive_esb_trigger(&pq);
1991         break;
1992 
1993     case XIVE_ESB_STORE_EOI ... XIVE_ESB_STORE_EOI + 0x3FF:
1994         /* TODO: can we check StoreEOI availability from the router ? */
1995         notify = xive_esb_eoi(&pq);
1996         break;
1997 
1998     case XIVE_ESB_INJECT ... XIVE_ESB_INJECT + 0x3FF:
1999         if (end_esmask == END2_W1_ESe) {
2000             qemu_log_mask(LOG_GUEST_ERROR,
2001                           "XIVE: END %x/%x can not EQ inject on ESe\n",
2002                            end_blk, end_idx);
2003             return;
2004         }
2005         notify = true;
2006         break;
2007 
2008     default:
2009         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: invalid END ESB write addr %d\n",
2010                       offset);
2011         return;
2012     }
2013 
2014     if (pq != xive_get_field32(end_esmask, end.w1)) {
2015         end.w1 = xive_set_field32(end_esmask, end.w1, pq);
2016         xive2_router_write_end(xsrc->xrtr, end_blk, end_idx, &end, 1);
2017     }
2018 
2019     /* TODO: Forward the source event notification for routing */
2020     if (notify) {
2021         ;
2022     }
2023 }
2024 
2025 static const MemoryRegionOps xive2_end_source_ops = {
2026     .read = xive2_end_source_read,
2027     .write = xive2_end_source_write,
2028     .endianness = DEVICE_BIG_ENDIAN,
2029     .valid = {
2030         .min_access_size = 1,
2031         .max_access_size = 8,
2032     },
2033     .impl = {
2034         .min_access_size = 1,
2035         .max_access_size = 8,
2036     },
2037 };
2038 
2039 static void xive2_end_source_realize(DeviceState *dev, Error **errp)
2040 {
2041     Xive2EndSource *xsrc = XIVE2_END_SOURCE(dev);
2042 
2043     assert(xsrc->xrtr);
2044 
2045     if (!xsrc->nr_ends) {
2046         error_setg(errp, "Number of interrupt needs to be greater than 0");
2047         return;
2048     }
2049 
2050     if (xsrc->esb_shift != XIVE_ESB_4K &&
2051         xsrc->esb_shift != XIVE_ESB_64K) {
2052         error_setg(errp, "Invalid ESB shift setting");
2053         return;
2054     }
2055 
2056     /*
2057      * Each END is assigned an even/odd pair of MMIO pages, the even page
2058      * manages the ESn field while the odd page manages the ESe field.
2059      */
2060     memory_region_init_io(&xsrc->esb_mmio, OBJECT(xsrc),
2061                           &xive2_end_source_ops, xsrc, "xive.end",
2062                           (1ull << (xsrc->esb_shift + 1)) * xsrc->nr_ends);
2063 }
2064 
2065 static const Property xive2_end_source_properties[] = {
2066     DEFINE_PROP_UINT32("nr-ends", Xive2EndSource, nr_ends, 0),
2067     DEFINE_PROP_UINT32("shift", Xive2EndSource, esb_shift, XIVE_ESB_64K),
2068     DEFINE_PROP_LINK("xive", Xive2EndSource, xrtr, TYPE_XIVE2_ROUTER,
2069                      Xive2Router *),
2070 };
2071 
2072 static void xive2_end_source_class_init(ObjectClass *klass, const void *data)
2073 {
2074     DeviceClass *dc = DEVICE_CLASS(klass);
2075 
2076     dc->desc    = "XIVE END Source";
2077     device_class_set_props(dc, xive2_end_source_properties);
2078     dc->realize = xive2_end_source_realize;
2079     dc->user_creatable = false;
2080 }
2081 
2082 static const TypeInfo xive2_end_source_info = {
2083     .name          = TYPE_XIVE2_END_SOURCE,
2084     .parent        = TYPE_DEVICE,
2085     .instance_size = sizeof(Xive2EndSource),
2086     .class_init    = xive2_end_source_class_init,
2087 };
2088 
2089 static void xive2_register_types(void)
2090 {
2091     type_register_static(&xive2_router_info);
2092     type_register_static(&xive2_end_source_info);
2093 }
2094 
2095 type_init(xive2_register_types)
2096