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