xref: /openbmc/qemu/hw/intc/xive2.c (revision d16214ed2c57a31b5de7e2c115c65b831170a60e)
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 *regs = &tctx->regs[ring];
610     uint8_t *alt_regs = (ring == TM_QW2_HV_POOL) ? &tctx->regs[TM_QW3_HV_PHYS] :
611                                                    regs;
612     uint8_t nsr = alt_regs[TM_NSR];
613     uint8_t pipr = alt_regs[TM_PIPR];
614     uint8_t crowd = NVx_CROWD_LVL(nsr);
615     uint8_t group = NVx_GROUP_LVL(nsr);
616     uint8_t nvgc_blk, end_blk, nvp_blk;
617     uint32_t nvgc_idx, end_idx, nvp_idx;
618     Xive2Nvgc nvgc;
619     uint8_t prio_limit;
620     uint32_t cfg;
621     uint8_t alt_ring;
622 
623     /* redistribution is only for group/crowd interrupts */
624     if (!xive_nsr_indicates_group_exception(ring, nsr)) {
625         return;
626     }
627 
628     alt_ring = xive_nsr_exception_ring(ring, nsr);
629 
630     /* Don't check return code since ring is expected to be invalidated */
631     xive2_tctx_get_nvp_indexes(tctx, alt_ring, &nvp_blk, &nvp_idx);
632 
633     trace_xive_redistribute(tctx->cs->cpu_index, alt_ring, nvp_blk, nvp_idx);
634 
635     trace_xive_redistribute(tctx->cs->cpu_index, ring, nvp_blk, nvp_idx);
636     /* convert crowd/group to blk/idx */
637     if (group > 0) {
638         nvgc_idx = (nvp_idx & (0xffffffff << group)) |
639                    ((1 << (group - 1)) - 1);
640     } else {
641         nvgc_idx = nvp_idx;
642     }
643 
644     if (crowd > 0) {
645         crowd = (crowd == 3) ? 4 : crowd;
646         nvgc_blk = (nvp_blk & (0xffffffff << crowd)) |
647                    ((1 << (crowd - 1)) - 1);
648     } else {
649         nvgc_blk = nvp_blk;
650     }
651 
652     /* Use blk/idx to retrieve the NVGC */
653     if (xive2_router_get_nvgc(xrtr, crowd, nvgc_blk, nvgc_idx, &nvgc)) {
654         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: no %s %x/%x\n",
655                       crowd ? "NVC" : "NVG", nvgc_blk, nvgc_idx);
656         return;
657     }
658 
659     /* retrieve the END blk/idx from the NVGC */
660     end_blk = xive_get_field32(NVGC2_W1_END_BLK, nvgc.w1);
661     end_idx = xive_get_field32(NVGC2_W1_END_IDX, nvgc.w1);
662 
663     /* determine number of priorities being used */
664     cfg = xive2_router_get_config(xrtr);
665     if (cfg & XIVE2_EN_VP_GRP_PRIORITY) {
666         prio_limit = 1 << GETFIELD(NVGC2_W1_PSIZE, nvgc.w1);
667     } else {
668         prio_limit = 1 << GETFIELD(XIVE2_VP_INT_PRIO, cfg);
669     }
670 
671     /* add priority offset to end index */
672     end_idx += pipr % prio_limit;
673 
674     /* trigger the group END */
675     xive2_router_end_notify(xrtr, end_blk, end_idx, 0, true);
676 
677     /* clear interrupt indication for the context */
678     alt_regs[TM_NSR] = 0;
679     alt_regs[TM_PIPR] = alt_regs[TM_CPPR];
680     xive_tctx_reset_signal(tctx, ring);
681 }
682 
683 static uint8_t xive2_hv_irq_ring(uint8_t nsr)
684 {
685     switch (nsr >> 6) {
686     case TM_QW3_NSR_HE_POOL:
687         return TM_QW2_HV_POOL;
688     case TM_QW3_NSR_HE_PHYS:
689         return TM_QW3_HV_PHYS;
690     default:
691         return -1;
692     }
693 }
694 
695 static uint64_t xive2_tm_pull_ctx(XivePresenter *xptr, XiveTCTX *tctx,
696                                   hwaddr offset, unsigned size, uint8_t ring)
697 {
698     Xive2Router *xrtr = XIVE2_ROUTER(xptr);
699     uint32_t target_ringw2 = xive_tctx_word2(&tctx->regs[ring]);
700     uint32_t cam = be32_to_cpu(target_ringw2);
701     uint8_t nvp_blk;
702     uint32_t nvp_idx;
703     uint8_t cur_ring;
704     bool valid;
705     bool do_save;
706     uint8_t nsr;
707 
708     xive2_cam_decode(cam, &nvp_blk, &nvp_idx, &valid, &do_save);
709 
710     if (xive2_tctx_get_nvp_indexes(tctx, ring, &nvp_blk, &nvp_idx)) {
711         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: pulling invalid NVP %x/%x !?\n",
712                       nvp_blk, nvp_idx);
713     }
714 
715     /* Invalidate CAM line of requested ring and all lower rings */
716     for (cur_ring = TM_QW0_USER; cur_ring <= ring;
717          cur_ring += XIVE_TM_RING_SIZE) {
718         uint32_t ringw2 = xive_tctx_word2(&tctx->regs[cur_ring]);
719         uint32_t ringw2_new = xive_set_field32(TM2_QW1W2_VO, ringw2, 0);
720         bool is_valid = !!(xive_get_field32(TM2_QW1W2_VO, ringw2));
721         uint8_t alt_ring;
722         memcpy(&tctx->regs[cur_ring + TM_WORD2], &ringw2_new, 4);
723 
724         /* Skip the rest for USER or invalid contexts */
725         if ((cur_ring == TM_QW0_USER) || !is_valid) {
726             continue;
727         }
728 
729         /* Active group/crowd interrupts need to be redistributed */
730         alt_ring = (cur_ring == TM_QW2_HV_POOL) ? TM_QW3_HV_PHYS : cur_ring;
731         nsr = tctx->regs[alt_ring + TM_NSR];
732         if (xive_nsr_indicates_group_exception(alt_ring, nsr)) {
733             /* For HV rings, only redistribute if cur_ring matches NSR */
734             if ((cur_ring == TM_QW1_OS) ||
735                 (cur_ring == xive2_hv_irq_ring(nsr))) {
736                 xive2_redistribute(xrtr, tctx, cur_ring);
737             }
738         }
739     }
740 
741     if (xive2_router_get_config(xrtr) & XIVE2_VP_SAVE_RESTORE && do_save) {
742         xive2_tctx_save_ctx(xrtr, tctx, nvp_blk, nvp_idx, ring);
743     }
744 
745     /*
746      * Lower external interrupt line of requested ring and below except for
747      * USER, which doesn't exist.
748      */
749     for (cur_ring = TM_QW1_OS; cur_ring <= ring;
750          cur_ring += XIVE_TM_RING_SIZE) {
751         xive_tctx_reset_signal(tctx, cur_ring);
752     }
753     return target_ringw2;
754 }
755 
756 uint64_t xive2_tm_pull_os_ctx(XivePresenter *xptr, XiveTCTX *tctx,
757                               hwaddr offset, unsigned size)
758 {
759     return xive2_tm_pull_ctx(xptr, tctx, offset, size, TM_QW1_OS);
760 }
761 
762 uint64_t xive2_tm_pull_pool_ctx(XivePresenter *xptr, XiveTCTX *tctx,
763                                 hwaddr offset, unsigned size)
764 {
765     return xive2_tm_pull_ctx(xptr, tctx, offset, size, TM_QW2_HV_POOL);
766 }
767 
768 uint64_t xive2_tm_pull_phys_ctx(XivePresenter *xptr, XiveTCTX *tctx,
769                                 hwaddr offset, unsigned size)
770 {
771     return xive2_tm_pull_ctx(xptr, tctx, offset, size, TM_QW3_HV_PHYS);
772 }
773 
774 #define REPORT_LINE_GEN1_SIZE       16
775 
776 static void xive2_tm_report_line_gen1(XiveTCTX *tctx, uint8_t *data,
777                                       uint8_t size)
778 {
779     uint8_t *regs = tctx->regs;
780 
781     g_assert(size == REPORT_LINE_GEN1_SIZE);
782     memset(data, 0, size);
783     /*
784      * See xive architecture for description of what is saved. It is
785      * hand-picked information to fit in 16 bytes.
786      */
787     data[0x0] = regs[TM_QW3_HV_PHYS + TM_NSR];
788     data[0x1] = regs[TM_QW3_HV_PHYS + TM_CPPR];
789     data[0x2] = regs[TM_QW3_HV_PHYS + TM_IPB];
790     data[0x3] = regs[TM_QW2_HV_POOL + TM_IPB];
791     data[0x4] = regs[TM_QW1_OS + TM_ACK_CNT];
792     data[0x5] = regs[TM_QW3_HV_PHYS + TM_LGS];
793     data[0x6] = 0xFF;
794     data[0x7] = regs[TM_QW3_HV_PHYS + TM_WORD2] & 0x80;
795     data[0x7] |= (regs[TM_QW2_HV_POOL + TM_WORD2] & 0x80) >> 1;
796     data[0x7] |= (regs[TM_QW1_OS + TM_WORD2] & 0x80) >> 2;
797     data[0x7] |= (regs[TM_QW3_HV_PHYS + TM_WORD2] & 0x3);
798     data[0x8] = regs[TM_QW1_OS + TM_NSR];
799     data[0x9] = regs[TM_QW1_OS + TM_CPPR];
800     data[0xA] = regs[TM_QW1_OS + TM_IPB];
801     data[0xB] = regs[TM_QW1_OS + TM_LGS];
802     if (regs[TM_QW0_USER + TM_WORD2] & 0x80) {
803         /*
804          * Logical server extension, except VU bit replaced by EB bit
805          * from NSR
806          */
807         data[0xC] = regs[TM_QW0_USER + TM_WORD2];
808         data[0xC] &= ~0x80;
809         data[0xC] |= regs[TM_QW0_USER + TM_NSR] & 0x80;
810         data[0xD] = regs[TM_QW0_USER + TM_WORD2 + 1];
811         data[0xE] = regs[TM_QW0_USER + TM_WORD2 + 2];
812         data[0xF] = regs[TM_QW0_USER + TM_WORD2 + 3];
813     }
814 }
815 
816 static void xive2_tm_pull_ctx_ol(XivePresenter *xptr, XiveTCTX *tctx,
817                                  hwaddr offset, uint64_t value,
818                                  unsigned size, uint8_t ring)
819 {
820     Xive2Router *xrtr = XIVE2_ROUTER(xptr);
821     uint32_t hw_cam, nvp_idx, xive2_cfg, reserved;
822     uint8_t nvp_blk;
823     Xive2Nvp nvp;
824     uint64_t phys_addr;
825     MemTxResult result;
826 
827     hw_cam = xive2_tctx_hw_cam_line(xptr, tctx);
828     nvp_blk = xive2_nvp_blk(hw_cam);
829     nvp_idx = xive2_nvp_idx(hw_cam);
830 
831     if (xive2_router_get_nvp(xrtr, nvp_blk, nvp_idx, &nvp)) {
832         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: No NVP %x/%x\n",
833                       nvp_blk, nvp_idx);
834         return;
835     }
836 
837     if (!xive2_nvp_is_valid(&nvp)) {
838         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: invalid NVP %x/%x\n",
839                       nvp_blk, nvp_idx);
840         return;
841     }
842 
843     xive2_cfg = xive2_router_get_config(xrtr);
844 
845     phys_addr = xive2_nvp_reporting_addr(&nvp) + 0x80; /* odd line */
846     if (xive2_cfg & XIVE2_GEN1_TIMA_OS) {
847         uint8_t pull_ctxt[REPORT_LINE_GEN1_SIZE];
848 
849         xive2_tm_report_line_gen1(tctx, pull_ctxt, REPORT_LINE_GEN1_SIZE);
850         result = dma_memory_write(&address_space_memory, phys_addr,
851                                   pull_ctxt, REPORT_LINE_GEN1_SIZE,
852                                   MEMTXATTRS_UNSPECIFIED);
853         assert(result == MEMTX_OK);
854     } else {
855         result = dma_memory_write(&address_space_memory, phys_addr,
856                                   &tctx->regs, sizeof(tctx->regs),
857                                   MEMTXATTRS_UNSPECIFIED);
858         assert(result == MEMTX_OK);
859         reserved = 0xFFFFFFFF;
860         result = dma_memory_write(&address_space_memory, phys_addr + 12,
861                                   &reserved, sizeof(reserved),
862                                   MEMTXATTRS_UNSPECIFIED);
863         assert(result == MEMTX_OK);
864     }
865 
866     /* the rest is similar to pull context to registers */
867     xive2_tm_pull_ctx(xptr, tctx, offset, size, ring);
868 }
869 
870 void xive2_tm_pull_os_ctx_ol(XivePresenter *xptr, XiveTCTX *tctx,
871                              hwaddr offset, uint64_t value, unsigned size)
872 {
873     xive2_tm_pull_ctx_ol(xptr, tctx, offset, value, size, TM_QW1_OS);
874 }
875 
876 
877 void xive2_tm_pull_phys_ctx_ol(XivePresenter *xptr, XiveTCTX *tctx,
878                                hwaddr offset, uint64_t value, unsigned size)
879 {
880     xive2_tm_pull_ctx_ol(xptr, tctx, offset, value, size, TM_QW3_HV_PHYS);
881 }
882 
883 static uint8_t xive2_tctx_restore_os_ctx(Xive2Router *xrtr, XiveTCTX *tctx,
884                                         uint8_t nvp_blk, uint32_t nvp_idx,
885                                         Xive2Nvp *nvp)
886 {
887     CPUPPCState *env = &POWERPC_CPU(tctx->cs)->env;
888     uint32_t pir = env->spr_cb[SPR_PIR].default_value;
889     uint8_t cppr;
890 
891     if (!xive2_nvp_is_hw(nvp)) {
892         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: NVP %x/%x is not HW owned\n",
893                       nvp_blk, nvp_idx);
894         return 0;
895     }
896 
897     cppr = xive_get_field32(NVP2_W2_CPPR, nvp->w2);
898     nvp->w2 = xive_set_field32(NVP2_W2_CPPR, nvp->w2, 0);
899     xive2_router_write_nvp(xrtr, nvp_blk, nvp_idx, nvp, 2);
900 
901     tctx->regs[TM_QW1_OS + TM_CPPR] = cppr;
902     tctx->regs[TM_QW1_OS + TM_LSMFB] = xive_get_field32(NVP2_W2_LSMFB, nvp->w2);
903     tctx->regs[TM_QW1_OS + TM_LGS] = xive_get_field32(NVP2_W2_LGS, nvp->w2);
904     tctx->regs[TM_QW1_OS + TM_T] = xive_get_field32(NVP2_W2_T, nvp->w2);
905 
906     nvp->w1 = xive_set_field32(NVP2_W1_CO, nvp->w1, 1);
907     nvp->w1 = xive_set_field32(NVP2_W1_CO_THRID_VALID, nvp->w1, 1);
908     nvp->w1 = xive_set_field32(NVP2_W1_CO_THRID, nvp->w1, pir);
909 
910     /*
911      * Checkout privilege: 0:OS, 1:Pool, 2:Hard
912      *
913      * TODO: we only support OS push/pull
914      */
915     nvp->w1 = xive_set_field32(NVP2_W1_CO_PRIV, nvp->w1, 0);
916 
917     xive2_router_write_nvp(xrtr, nvp_blk, nvp_idx, nvp, 1);
918 
919     /* return restored CPPR to generate a CPU exception if needed */
920     return cppr;
921 }
922 
923 static void xive2_tctx_need_resend(Xive2Router *xrtr, XiveTCTX *tctx,
924                                    uint8_t nvp_blk, uint32_t nvp_idx,
925                                    bool do_restore)
926 {
927     XivePresenter *xptr = XIVE_PRESENTER(xrtr);
928     uint8_t ipb;
929     uint8_t backlog_level;
930     uint8_t group_level;
931     uint8_t first_group;
932     uint8_t backlog_prio;
933     uint8_t group_prio;
934     uint8_t *regs = &tctx->regs[TM_QW1_OS];
935     Xive2Nvp nvp;
936 
937     /*
938      * Grab the associated thread interrupt context registers in the
939      * associated NVP
940      */
941     if (xive2_router_get_nvp(xrtr, nvp_blk, nvp_idx, &nvp)) {
942         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: No NVP %x/%x\n",
943                       nvp_blk, nvp_idx);
944         return;
945     }
946 
947     if (!xive2_nvp_is_valid(&nvp)) {
948         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: invalid NVP %x/%x\n",
949                       nvp_blk, nvp_idx);
950         return;
951     }
952 
953     /* Automatically restore thread context registers */
954     if (xive2_router_get_config(xrtr) & XIVE2_VP_SAVE_RESTORE &&
955         do_restore) {
956         xive2_tctx_restore_os_ctx(xrtr, tctx, nvp_blk, nvp_idx, &nvp);
957     }
958 
959     ipb = xive_get_field32(NVP2_W2_IPB, nvp.w2);
960     if (ipb) {
961         nvp.w2 = xive_set_field32(NVP2_W2_IPB, nvp.w2, 0);
962         xive2_router_write_nvp(xrtr, nvp_blk, nvp_idx, &nvp, 2);
963     }
964     /* IPB bits in the backlog are merged with the TIMA IPB bits */
965     regs[TM_IPB] |= ipb;
966     backlog_prio = xive_ipb_to_pipr(regs[TM_IPB]);
967     backlog_level = 0;
968 
969     first_group = xive_get_field32(NVP2_W0_PGOFIRST, nvp.w0);
970     if (first_group && regs[TM_LSMFB] < backlog_prio) {
971         group_prio = xive2_presenter_backlog_scan(xptr, nvp_blk, nvp_idx,
972                                                   first_group, &group_level);
973         regs[TM_LSMFB] = group_prio;
974         if (regs[TM_LGS] && group_prio < backlog_prio &&
975             group_prio < regs[TM_CPPR]) {
976 
977             /* VP can take a group interrupt */
978             xive2_presenter_backlog_decr(xptr, nvp_blk, nvp_idx,
979                                          group_prio, group_level);
980             backlog_prio = group_prio;
981             backlog_level = group_level;
982         }
983     }
984 
985     /*
986      * Compute the PIPR based on the restored state.
987      * It will raise the External interrupt signal if needed.
988      */
989     xive_tctx_pipr_update(tctx, TM_QW1_OS, backlog_prio, backlog_level);
990 }
991 
992 /*
993  * Updating the OS CAM line can trigger a resend of interrupt
994  */
995 void xive2_tm_push_os_ctx(XivePresenter *xptr, XiveTCTX *tctx,
996                           hwaddr offset, uint64_t value, unsigned size)
997 {
998     uint32_t cam;
999     uint32_t qw1w2;
1000     uint64_t qw1dw1;
1001     uint8_t nvp_blk;
1002     uint32_t nvp_idx;
1003     bool vo;
1004     bool do_restore;
1005 
1006     /* First update the thead context */
1007     switch (size) {
1008     case 4:
1009         cam = value;
1010         qw1w2 = cpu_to_be32(cam);
1011         memcpy(&tctx->regs[TM_QW1_OS + TM_WORD2], &qw1w2, 4);
1012         break;
1013     case 8:
1014         cam = value >> 32;
1015         qw1dw1 = cpu_to_be64(value);
1016         memcpy(&tctx->regs[TM_QW1_OS + TM_WORD2], &qw1dw1, 8);
1017         break;
1018     default:
1019         g_assert_not_reached();
1020     }
1021 
1022     xive2_cam_decode(cam, &nvp_blk, &nvp_idx, &vo, &do_restore);
1023 
1024     /* Check the interrupt pending bits */
1025     if (vo) {
1026         xive2_tctx_need_resend(XIVE2_ROUTER(xptr), tctx, nvp_blk, nvp_idx,
1027                                do_restore);
1028     }
1029 }
1030 
1031 /* returns -1 if ring is invalid, but still populates block and index */
1032 static int xive2_tctx_get_nvp_indexes(XiveTCTX *tctx, uint8_t ring,
1033                                       uint8_t *nvp_blk, uint32_t *nvp_idx)
1034 {
1035     uint32_t w2;
1036     uint32_t cam = 0;
1037     int rc = 0;
1038 
1039     w2 = xive_tctx_word2(&tctx->regs[ring]);
1040     switch (ring) {
1041     case TM_QW1_OS:
1042         if (!(be32_to_cpu(w2) & TM2_QW1W2_VO)) {
1043             rc = -1;
1044         }
1045         cam = xive_get_field32(TM2_QW1W2_OS_CAM, w2);
1046         break;
1047     case TM_QW2_HV_POOL:
1048         if (!(be32_to_cpu(w2) & TM2_QW2W2_VP)) {
1049             rc = -1;
1050         }
1051         cam = xive_get_field32(TM2_QW2W2_POOL_CAM, w2);
1052         break;
1053     case TM_QW3_HV_PHYS:
1054         if (!(be32_to_cpu(w2) & TM2_QW3W2_VT)) {
1055             rc = -1;
1056         }
1057         cam = xive2_tctx_hw_cam_line(tctx->xptr, tctx);
1058         break;
1059     default:
1060         rc = -1;
1061     }
1062     *nvp_blk = xive2_nvp_blk(cam);
1063     *nvp_idx = xive2_nvp_idx(cam);
1064     return rc;
1065 }
1066 
1067 static void xive2_tctx_accept_el(XivePresenter *xptr, XiveTCTX *tctx,
1068                                  uint8_t ring, uint8_t cl_ring)
1069 {
1070     uint64_t rd;
1071     Xive2Router *xrtr = XIVE2_ROUTER(xptr);
1072     uint32_t nvp_idx, xive2_cfg;
1073     uint8_t nvp_blk;
1074     Xive2Nvp nvp;
1075     uint64_t phys_addr;
1076     uint8_t OGen = 0;
1077 
1078     xive2_tctx_get_nvp_indexes(tctx, cl_ring, &nvp_blk, &nvp_idx);
1079 
1080     if (xive2_router_get_nvp(xrtr, (uint8_t)nvp_blk, nvp_idx, &nvp)) {
1081         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: No NVP %x/%x\n",
1082                       nvp_blk, nvp_idx);
1083         return;
1084     }
1085 
1086     if (!xive2_nvp_is_valid(&nvp)) {
1087         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: invalid NVP %x/%x\n",
1088                       nvp_blk, nvp_idx);
1089         return;
1090     }
1091 
1092 
1093     rd = xive_tctx_accept(tctx, ring);
1094 
1095     if (ring == TM_QW1_OS) {
1096         OGen = tctx->regs[ring + TM_OGEN];
1097     }
1098     xive2_cfg = xive2_router_get_config(xrtr);
1099     phys_addr = xive2_nvp_reporting_addr(&nvp);
1100     uint8_t report_data[REPORT_LINE_GEN1_SIZE];
1101     memset(report_data, 0xff, sizeof(report_data));
1102     if ((OGen == 1) || (xive2_cfg & XIVE2_GEN1_TIMA_OS)) {
1103         report_data[8] = (rd >> 8) & 0xff;
1104         report_data[9] = rd & 0xff;
1105     } else {
1106         report_data[0] = (rd >> 8) & 0xff;
1107         report_data[1] = rd & 0xff;
1108     }
1109     cpu_physical_memory_write(phys_addr, report_data, REPORT_LINE_GEN1_SIZE);
1110 }
1111 
1112 void xive2_tm_ack_os_el(XivePresenter *xptr, XiveTCTX *tctx,
1113                         hwaddr offset, uint64_t value, unsigned size)
1114 {
1115     xive2_tctx_accept_el(xptr, tctx, TM_QW1_OS, TM_QW1_OS);
1116 }
1117 
1118 /* NOTE: CPPR only exists for TM_QW1_OS and TM_QW3_HV_PHYS */
1119 static void xive2_tctx_set_cppr(XiveTCTX *tctx, uint8_t ring, uint8_t cppr)
1120 {
1121     uint8_t *regs = &tctx->regs[ring];
1122     Xive2Router *xrtr = XIVE2_ROUTER(tctx->xptr);
1123     uint8_t old_cppr, backlog_prio, first_group, group_level;
1124     uint8_t pipr_min, lsmfb_min, ring_min;
1125     bool group_enabled;
1126     uint8_t nvp_blk;
1127     uint32_t nvp_idx;
1128     Xive2Nvp nvp;
1129     int rc;
1130     uint8_t nsr = regs[TM_NSR];
1131 
1132     trace_xive_tctx_set_cppr(tctx->cs->cpu_index, ring,
1133                              regs[TM_IPB], regs[TM_PIPR],
1134                              cppr, nsr);
1135 
1136     if (cppr > XIVE_PRIORITY_MAX) {
1137         cppr = 0xff;
1138     }
1139 
1140     old_cppr = regs[TM_CPPR];
1141     regs[TM_CPPR] = cppr;
1142 
1143     /* Handle increased CPPR priority (lower value) */
1144     if (cppr < old_cppr) {
1145         if (cppr <= regs[TM_PIPR]) {
1146             /* CPPR lowered below PIPR, must un-present interrupt */
1147             if (xive_nsr_indicates_exception(ring, nsr)) {
1148                 if (xive_nsr_indicates_group_exception(ring, nsr)) {
1149                     /* redistribute precluded active grp interrupt */
1150                     xive2_redistribute(xrtr, tctx, ring);
1151                     return;
1152                 }
1153             }
1154 
1155             /* interrupt is VP directed, pending in IPB */
1156             regs[TM_PIPR] = cppr;
1157             xive_tctx_notify(tctx, ring, 0); /* Ensure interrupt is cleared */
1158             return;
1159         } else {
1160             /* CPPR was lowered, but still above PIPR. No action needed. */
1161             return;
1162         }
1163     }
1164 
1165     /* CPPR didn't change, nothing needs to be done */
1166     if (cppr == old_cppr) {
1167         return;
1168     }
1169 
1170     /* CPPR priority decreased (higher value) */
1171 
1172     /*
1173      * Recompute the PIPR based on local pending interrupts. It will
1174      * be adjusted below if needed in case of pending group interrupts.
1175      */
1176 again:
1177     pipr_min = xive_ipb_to_pipr(regs[TM_IPB]);
1178     group_enabled = !!regs[TM_LGS];
1179     lsmfb_min = group_enabled ? regs[TM_LSMFB] : 0xff;
1180     ring_min = ring;
1181     group_level = 0;
1182 
1183     /* PHYS updates also depend on POOL values */
1184     if (ring == TM_QW3_HV_PHYS) {
1185         uint8_t *pool_regs = &tctx->regs[TM_QW2_HV_POOL];
1186 
1187         /* POOL values only matter if POOL ctx is valid */
1188         if (pool_regs[TM_WORD2] & 0x80) {
1189             uint8_t pool_pipr = xive_ipb_to_pipr(pool_regs[TM_IPB]);
1190             uint8_t pool_lsmfb = pool_regs[TM_LSMFB];
1191 
1192             /*
1193              * Determine highest priority interrupt and
1194              * remember which ring has it.
1195              */
1196             if (pool_pipr < pipr_min) {
1197                 pipr_min = pool_pipr;
1198                 if (pool_pipr < lsmfb_min) {
1199                     ring_min = TM_QW2_HV_POOL;
1200                 }
1201             }
1202 
1203             /* Values needed for group priority calculation */
1204             if (pool_regs[TM_LGS] && (pool_lsmfb < lsmfb_min)) {
1205                 group_enabled = true;
1206                 lsmfb_min = pool_lsmfb;
1207                 if (lsmfb_min < pipr_min) {
1208                     ring_min = TM_QW2_HV_POOL;
1209                 }
1210             }
1211         }
1212     }
1213 
1214     rc = xive2_tctx_get_nvp_indexes(tctx, ring_min, &nvp_blk, &nvp_idx);
1215     if (rc) {
1216         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: set CPPR on invalid context\n");
1217         return;
1218     }
1219 
1220     if (group_enabled &&
1221         lsmfb_min < cppr &&
1222         lsmfb_min < pipr_min) {
1223         /*
1224          * Thread has seen a group interrupt with a higher priority
1225          * than the new cppr or pending local interrupt. Check the
1226          * backlog
1227          */
1228         if (xive2_router_get_nvp(xrtr, nvp_blk, nvp_idx, &nvp)) {
1229             qemu_log_mask(LOG_GUEST_ERROR, "XIVE: No NVP %x/%x\n",
1230                           nvp_blk, nvp_idx);
1231             return;
1232         }
1233 
1234         if (!xive2_nvp_is_valid(&nvp)) {
1235             qemu_log_mask(LOG_GUEST_ERROR, "XIVE: invalid NVP %x/%x\n",
1236                           nvp_blk, nvp_idx);
1237             return;
1238         }
1239 
1240         first_group = xive_get_field32(NVP2_W0_PGOFIRST, nvp.w0);
1241         if (!first_group) {
1242             qemu_log_mask(LOG_GUEST_ERROR, "XIVE: invalid NVP %x/%x\n",
1243                           nvp_blk, nvp_idx);
1244             return;
1245         }
1246 
1247         backlog_prio = xive2_presenter_backlog_scan(tctx->xptr,
1248                                                     nvp_blk, nvp_idx,
1249                                                     first_group, &group_level);
1250         tctx->regs[ring_min + TM_LSMFB] = backlog_prio;
1251         if (backlog_prio != lsmfb_min) {
1252             /*
1253              * If the group backlog scan finds a less favored or no interrupt,
1254              * then re-do the processing which may turn up a more favored
1255              * interrupt from IPB or the other pool. Backlog should not
1256              * find a priority < LSMFB.
1257              */
1258             g_assert(backlog_prio >= lsmfb_min);
1259             goto again;
1260         }
1261 
1262         xive2_presenter_backlog_decr(tctx->xptr, nvp_blk, nvp_idx,
1263                                      backlog_prio, group_level);
1264         pipr_min = backlog_prio;
1265     }
1266 
1267     /* PIPR should not be set to a value greater than CPPR */
1268     regs[TM_PIPR] = (pipr_min > cppr) ? cppr : pipr_min;
1269 
1270     /* CPPR has changed, check if we need to raise a pending exception */
1271     xive_tctx_notify(tctx, ring_min, group_level);
1272 }
1273 
1274 void xive2_tm_set_hv_cppr(XivePresenter *xptr, XiveTCTX *tctx,
1275                           hwaddr offset, uint64_t value, unsigned size)
1276 {
1277     xive2_tctx_set_cppr(tctx, TM_QW3_HV_PHYS, value & 0xff);
1278 }
1279 
1280 void xive2_tm_set_os_cppr(XivePresenter *xptr, XiveTCTX *tctx,
1281                           hwaddr offset, uint64_t value, unsigned size)
1282 {
1283     xive2_tctx_set_cppr(tctx, TM_QW1_OS, value & 0xff);
1284 }
1285 
1286 static void xive2_tctx_set_target(XiveTCTX *tctx, uint8_t ring, uint8_t target)
1287 {
1288     uint8_t *regs = &tctx->regs[ring];
1289 
1290     regs[TM_T] = target;
1291 }
1292 
1293 void xive2_tm_set_hv_target(XivePresenter *xptr, XiveTCTX *tctx,
1294                             hwaddr offset, uint64_t value, unsigned size)
1295 {
1296     xive2_tctx_set_target(tctx, TM_QW3_HV_PHYS, value & 0xff);
1297 }
1298 
1299 /*
1300  * XIVE Router (aka. Virtualization Controller or IVRE)
1301  */
1302 
1303 int xive2_router_get_eas(Xive2Router *xrtr, uint8_t eas_blk, uint32_t eas_idx,
1304                          Xive2Eas *eas)
1305 {
1306     Xive2RouterClass *xrc = XIVE2_ROUTER_GET_CLASS(xrtr);
1307 
1308     return xrc->get_eas(xrtr, eas_blk, eas_idx, eas);
1309 }
1310 
1311 static
1312 int xive2_router_get_pq(Xive2Router *xrtr, uint8_t eas_blk, uint32_t eas_idx,
1313                        uint8_t *pq)
1314 {
1315     Xive2RouterClass *xrc = XIVE2_ROUTER_GET_CLASS(xrtr);
1316 
1317     return xrc->get_pq(xrtr, eas_blk, eas_idx, pq);
1318 }
1319 
1320 static
1321 int xive2_router_set_pq(Xive2Router *xrtr, uint8_t eas_blk, uint32_t eas_idx,
1322                        uint8_t *pq)
1323 {
1324     Xive2RouterClass *xrc = XIVE2_ROUTER_GET_CLASS(xrtr);
1325 
1326     return xrc->set_pq(xrtr, eas_blk, eas_idx, pq);
1327 }
1328 
1329 int xive2_router_get_end(Xive2Router *xrtr, uint8_t end_blk, uint32_t end_idx,
1330                          Xive2End *end)
1331 {
1332    Xive2RouterClass *xrc = XIVE2_ROUTER_GET_CLASS(xrtr);
1333 
1334    return xrc->get_end(xrtr, end_blk, end_idx, end);
1335 }
1336 
1337 int xive2_router_write_end(Xive2Router *xrtr, uint8_t end_blk, uint32_t end_idx,
1338                            Xive2End *end, uint8_t word_number)
1339 {
1340    Xive2RouterClass *xrc = XIVE2_ROUTER_GET_CLASS(xrtr);
1341 
1342    return xrc->write_end(xrtr, end_blk, end_idx, end, word_number);
1343 }
1344 
1345 int xive2_router_get_nvp(Xive2Router *xrtr, uint8_t nvp_blk, uint32_t nvp_idx,
1346                          Xive2Nvp *nvp)
1347 {
1348    Xive2RouterClass *xrc = XIVE2_ROUTER_GET_CLASS(xrtr);
1349 
1350    return xrc->get_nvp(xrtr, nvp_blk, nvp_idx, nvp);
1351 }
1352 
1353 int xive2_router_write_nvp(Xive2Router *xrtr, uint8_t nvp_blk, uint32_t nvp_idx,
1354                            Xive2Nvp *nvp, uint8_t word_number)
1355 {
1356    Xive2RouterClass *xrc = XIVE2_ROUTER_GET_CLASS(xrtr);
1357 
1358    return xrc->write_nvp(xrtr, nvp_blk, nvp_idx, nvp, word_number);
1359 }
1360 
1361 int xive2_router_get_nvgc(Xive2Router *xrtr, bool crowd,
1362                           uint8_t nvgc_blk, uint32_t nvgc_idx,
1363                           Xive2Nvgc *nvgc)
1364 {
1365    Xive2RouterClass *xrc = XIVE2_ROUTER_GET_CLASS(xrtr);
1366 
1367    return xrc->get_nvgc(xrtr, crowd, nvgc_blk, nvgc_idx, nvgc);
1368 }
1369 
1370 int xive2_router_write_nvgc(Xive2Router *xrtr, bool crowd,
1371                             uint8_t nvgc_blk, uint32_t nvgc_idx,
1372                             Xive2Nvgc *nvgc)
1373 {
1374    Xive2RouterClass *xrc = XIVE2_ROUTER_GET_CLASS(xrtr);
1375 
1376    return xrc->write_nvgc(xrtr, crowd, nvgc_blk, nvgc_idx, nvgc);
1377 }
1378 
1379 static bool xive2_vp_match_mask(uint32_t cam1, uint32_t cam2,
1380                                 uint32_t vp_mask)
1381 {
1382     return (cam1 & vp_mask) == (cam2 & vp_mask);
1383 }
1384 
1385 static uint8_t xive2_get_vp_block_mask(uint32_t nvt_blk, bool crowd)
1386 {
1387     uint8_t block_mask = 0b1111;
1388 
1389     /* 3 supported crowd sizes: 2, 4, 16 */
1390     if (crowd) {
1391         uint32_t size = xive_get_vpgroup_size(nvt_blk);
1392 
1393         if (size != 2 && size != 4 && size != 16) {
1394             qemu_log_mask(LOG_GUEST_ERROR, "XIVE: Invalid crowd size of %d",
1395                                            size);
1396             return block_mask;
1397         }
1398         block_mask &= ~(size - 1);
1399     }
1400     return block_mask;
1401 }
1402 
1403 static uint32_t xive2_get_vp_index_mask(uint32_t nvt_index, bool cam_ignore)
1404 {
1405     uint32_t index_mask = 0xFFFFFF; /* 24 bits */
1406 
1407     if (cam_ignore) {
1408         uint32_t size = xive_get_vpgroup_size(nvt_index);
1409 
1410         if (size < 2) {
1411             qemu_log_mask(LOG_GUEST_ERROR, "XIVE: Invalid group size of %d",
1412                                            size);
1413             return index_mask;
1414         }
1415         index_mask &= ~(size - 1);
1416     }
1417     return index_mask;
1418 }
1419 
1420 /*
1421  * The thread context register words are in big-endian format.
1422  */
1423 int xive2_presenter_tctx_match(XivePresenter *xptr, XiveTCTX *tctx,
1424                                uint8_t format,
1425                                uint8_t nvt_blk, uint32_t nvt_idx,
1426                                bool crowd, bool cam_ignore,
1427                                uint32_t logic_serv)
1428 {
1429     uint32_t cam =   xive2_nvp_cam_line(nvt_blk, nvt_idx);
1430     uint32_t qw3w2 = xive_tctx_word2(&tctx->regs[TM_QW3_HV_PHYS]);
1431     uint32_t qw2w2 = xive_tctx_word2(&tctx->regs[TM_QW2_HV_POOL]);
1432     uint32_t qw1w2 = xive_tctx_word2(&tctx->regs[TM_QW1_OS]);
1433     uint32_t qw0w2 = xive_tctx_word2(&tctx->regs[TM_QW0_USER]);
1434 
1435     uint32_t index_mask, vp_mask;
1436     uint8_t block_mask;
1437 
1438     if (format == 0) {
1439         /*
1440          * i=0: Specific NVT notification
1441          * i=1: VP-group notification (bits ignored at the end of the
1442          *      NVT identifier)
1443          */
1444         block_mask = xive2_get_vp_block_mask(nvt_blk, crowd);
1445         index_mask = xive2_get_vp_index_mask(nvt_idx, cam_ignore);
1446         vp_mask = xive2_nvp_cam_line(block_mask, index_mask);
1447 
1448         /* For VP-group notifications, threads with LGS=0 are excluded */
1449 
1450         /* PHYS ring */
1451         if ((be32_to_cpu(qw3w2) & TM2_QW3W2_VT) &&
1452             !(cam_ignore && tctx->regs[TM_QW3_HV_PHYS + TM_LGS] == 0) &&
1453             xive2_vp_match_mask(cam,
1454                                 xive2_tctx_hw_cam_line(xptr, tctx),
1455                                 vp_mask)) {
1456             return TM_QW3_HV_PHYS;
1457         }
1458 
1459         /* HV POOL ring */
1460         if ((be32_to_cpu(qw2w2) & TM2_QW2W2_VP) &&
1461             !(cam_ignore && tctx->regs[TM_QW2_HV_POOL + TM_LGS] == 0) &&
1462             xive2_vp_match_mask(cam,
1463                                 xive_get_field32(TM2_QW2W2_POOL_CAM, qw2w2),
1464                                 vp_mask)) {
1465             return TM_QW2_HV_POOL;
1466         }
1467 
1468         /* OS ring */
1469         if ((be32_to_cpu(qw1w2) & TM2_QW1W2_VO) &&
1470             !(cam_ignore && tctx->regs[TM_QW1_OS + TM_LGS] == 0) &&
1471             xive2_vp_match_mask(cam,
1472                                 xive_get_field32(TM2_QW1W2_OS_CAM, qw1w2),
1473                                 vp_mask)) {
1474             return TM_QW1_OS;
1475         }
1476     } else {
1477         /* F=1 : User level Event-Based Branch (EBB) notification */
1478 
1479         /* FIXME: what if cam_ignore and LGS = 0 ? */
1480         /* USER ring */
1481         if  ((be32_to_cpu(qw1w2) & TM2_QW1W2_VO) &&
1482              (cam == xive_get_field32(TM2_QW1W2_OS_CAM, qw1w2)) &&
1483              (be32_to_cpu(qw0w2) & TM2_QW0W2_VU) &&
1484              (logic_serv == xive_get_field32(TM2_QW0W2_LOGIC_SERV, qw0w2))) {
1485             return TM_QW0_USER;
1486         }
1487     }
1488     return -1;
1489 }
1490 
1491 bool xive2_tm_irq_precluded(XiveTCTX *tctx, int ring, uint8_t priority)
1492 {
1493     /* HV_POOL ring uses HV_PHYS NSR, CPPR and PIPR registers */
1494     uint8_t alt_ring = (ring == TM_QW2_HV_POOL) ? TM_QW3_HV_PHYS : ring;
1495     uint8_t *alt_regs = &tctx->regs[alt_ring];
1496 
1497     /*
1498      * The xive2_presenter_tctx_match() above tells if there's a match
1499      * but for VP-group notification, we still need to look at the
1500      * priority to know if the thread can take the interrupt now or if
1501      * it is precluded.
1502      */
1503     if (priority < alt_regs[TM_PIPR]) {
1504         return false;
1505     }
1506     return true;
1507 }
1508 
1509 void xive2_tm_set_lsmfb(XiveTCTX *tctx, int ring, uint8_t priority)
1510 {
1511     uint8_t *regs = &tctx->regs[ring];
1512 
1513     /*
1514      * Called by the router during a VP-group notification when the
1515      * thread matches but can't take the interrupt because it's
1516      * already running at a more favored priority. It then stores the
1517      * new interrupt priority in the LSMFB field.
1518      */
1519     regs[TM_LSMFB] = priority;
1520 }
1521 
1522 static void xive2_router_realize(DeviceState *dev, Error **errp)
1523 {
1524     Xive2Router *xrtr = XIVE2_ROUTER(dev);
1525 
1526     assert(xrtr->xfb);
1527 }
1528 
1529 /*
1530  * Notification using the END ESe/ESn bit (Event State Buffer for
1531  * escalation and notification). Profide further coalescing in the
1532  * Router.
1533  */
1534 static bool xive2_router_end_es_notify(Xive2Router *xrtr, uint8_t end_blk,
1535                                        uint32_t end_idx, Xive2End *end,
1536                                        uint32_t end_esmask)
1537 {
1538     uint8_t pq = xive_get_field32(end_esmask, end->w1);
1539     bool notify = xive_esb_trigger(&pq);
1540 
1541     if (pq != xive_get_field32(end_esmask, end->w1)) {
1542         end->w1 = xive_set_field32(end_esmask, end->w1, pq);
1543         xive2_router_write_end(xrtr, end_blk, end_idx, end, 1);
1544     }
1545 
1546     /* ESe/n[Q]=1 : end of notification */
1547     return notify;
1548 }
1549 
1550 /*
1551  * An END trigger can come from an event trigger (IPI or HW) or from
1552  * another chip. We don't model the PowerBus but the END trigger
1553  * message has the same parameters than in the function below.
1554  */
1555 static void xive2_router_end_notify(Xive2Router *xrtr, uint8_t end_blk,
1556                                     uint32_t end_idx, uint32_t end_data,
1557                                     bool redistribute)
1558 {
1559     Xive2End end;
1560     uint8_t priority;
1561     uint8_t format;
1562     XiveTCTXMatch match;
1563     bool crowd, cam_ignore;
1564     uint8_t nvx_blk;
1565     uint32_t nvx_idx;
1566 
1567     /* END cache lookup */
1568     if (xive2_router_get_end(xrtr, end_blk, end_idx, &end)) {
1569         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: No END %x/%x\n", end_blk,
1570                       end_idx);
1571         return;
1572     }
1573 
1574     if (!xive2_end_is_valid(&end)) {
1575         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: END %x/%x is invalid\n",
1576                       end_blk, end_idx);
1577         return;
1578     }
1579 
1580     if (xive2_end_is_crowd(&end) && !xive2_end_is_ignore(&end)) {
1581         qemu_log_mask(LOG_GUEST_ERROR,
1582                       "XIVE: invalid END, 'crowd' bit requires 'ignore' bit\n");
1583         return;
1584     }
1585 
1586     if (!redistribute && xive2_end_is_enqueue(&end)) {
1587         trace_xive_end_enqueue(end_blk, end_idx, end_data);
1588         xive2_end_enqueue(&end, end_data);
1589         /* Enqueuing event data modifies the EQ toggle and index */
1590         xive2_router_write_end(xrtr, end_blk, end_idx, &end, 1);
1591     }
1592 
1593     /*
1594      * When the END is silent, we skip the notification part.
1595      */
1596     if (xive2_end_is_silent_escalation(&end)) {
1597         goto do_escalation;
1598     }
1599 
1600     /*
1601      * The W7 format depends on the F bit in W6. It defines the type
1602      * of the notification :
1603      *
1604      *   F=0 : single or multiple NVP notification
1605      *   F=1 : User level Event-Based Branch (EBB) notification, no
1606      *         priority
1607      */
1608     format = xive_get_field32(END2_W6_FORMAT_BIT, end.w6);
1609     priority = xive_get_field32(END2_W7_F0_PRIORITY, end.w7);
1610 
1611     /* The END is masked */
1612     if (format == 0 && priority == 0xff) {
1613         return;
1614     }
1615 
1616     /*
1617      * Check the END ESn (Event State Buffer for notification) for
1618      * even further coalescing in the Router
1619      */
1620     if (!xive2_end_is_notify(&end)) {
1621         /* ESn[Q]=1 : end of notification */
1622         if (!xive2_router_end_es_notify(xrtr, end_blk, end_idx,
1623                                        &end, END2_W1_ESn)) {
1624             return;
1625         }
1626     }
1627 
1628     /*
1629      * Follows IVPE notification
1630      */
1631     nvx_blk = xive_get_field32(END2_W6_VP_BLOCK, end.w6);
1632     nvx_idx = xive_get_field32(END2_W6_VP_OFFSET, end.w6);
1633     crowd = xive2_end_is_crowd(&end);
1634     cam_ignore = xive2_end_is_ignore(&end);
1635 
1636     /* TODO: Auto EOI. */
1637     if (xive_presenter_match(xrtr->xfb, format, nvx_blk, nvx_idx,
1638                              crowd, cam_ignore, priority,
1639                              xive_get_field32(END2_W7_F1_LOG_SERVER_ID, end.w7),
1640                              &match)) {
1641         XiveTCTX *tctx = match.tctx;
1642         uint8_t ring = match.ring;
1643         uint8_t alt_ring = (ring == TM_QW2_HV_POOL) ? TM_QW3_HV_PHYS : ring;
1644         uint8_t *aregs = &tctx->regs[alt_ring];
1645         uint8_t nsr = aregs[TM_NSR];
1646         uint8_t group_level;
1647 
1648         if (priority < aregs[TM_PIPR] &&
1649             xive_nsr_indicates_group_exception(alt_ring, nsr)) {
1650             xive2_redistribute(xrtr, tctx, alt_ring);
1651         }
1652 
1653         group_level = xive_get_group_level(crowd, cam_ignore, nvx_blk, nvx_idx);
1654         trace_xive_presenter_notify(nvx_blk, nvx_idx, ring, group_level);
1655         xive_tctx_pipr_present(tctx, ring, priority, group_level);
1656         return;
1657     }
1658 
1659     /*
1660      * If no matching NVP is dispatched on a HW thread :
1661      * - specific VP: update the NVP structure if backlog is activated
1662      * - VP-group: update the backlog counter for that priority in the NVG
1663      */
1664     if (xive2_end_is_backlog(&end)) {
1665 
1666         if (format == 1) {
1667             qemu_log_mask(LOG_GUEST_ERROR,
1668                           "XIVE: END %x/%x invalid config: F1 & backlog\n",
1669                           end_blk, end_idx);
1670             return;
1671         }
1672 
1673         if (!cam_ignore) {
1674             uint8_t ipb;
1675             Xive2Nvp nvp;
1676 
1677             /* NVP cache lookup */
1678             if (xive2_router_get_nvp(xrtr, nvx_blk, nvx_idx, &nvp)) {
1679                 qemu_log_mask(LOG_GUEST_ERROR, "XIVE: no NVP %x/%x\n",
1680                               nvx_blk, nvx_idx);
1681                 return;
1682             }
1683 
1684             if (!xive2_nvp_is_valid(&nvp)) {
1685                 qemu_log_mask(LOG_GUEST_ERROR, "XIVE: NVP %x/%x is invalid\n",
1686                               nvx_blk, nvx_idx);
1687                 return;
1688             }
1689 
1690             /*
1691              * Record the IPB in the associated NVP structure for later
1692              * use. The presenter will resend the interrupt when the vCPU
1693              * is dispatched again on a HW thread.
1694              */
1695             ipb = xive_get_field32(NVP2_W2_IPB, nvp.w2) |
1696                 xive_priority_to_ipb(priority);
1697             nvp.w2 = xive_set_field32(NVP2_W2_IPB, nvp.w2, ipb);
1698             xive2_router_write_nvp(xrtr, nvx_blk, nvx_idx, &nvp, 2);
1699         } else {
1700             Xive2Nvgc nvgc;
1701             uint32_t backlog;
1702 
1703             /*
1704              * For groups and crowds, the per-priority backlog
1705              * counters are stored in the NVG/NVC structures
1706              */
1707             if (xive2_router_get_nvgc(xrtr, crowd,
1708                                       nvx_blk, nvx_idx, &nvgc)) {
1709                 qemu_log_mask(LOG_GUEST_ERROR, "XIVE: no %s %x/%x\n",
1710                               crowd ? "NVC" : "NVG", nvx_blk, nvx_idx);
1711                 return;
1712             }
1713 
1714             if (!xive2_nvgc_is_valid(&nvgc)) {
1715                 qemu_log_mask(LOG_GUEST_ERROR, "XIVE: NVG %x/%x is invalid\n",
1716                               nvx_blk, nvx_idx);
1717                 return;
1718             }
1719 
1720             /*
1721              * Increment the backlog counter for that priority.
1722              * We only call broadcast the first time the counter is
1723              * incremented. broadcast will set the LSMFB field of the TIMA of
1724              * relevant threads so that they know an interrupt is pending.
1725              */
1726             backlog = xive2_nvgc_get_backlog(&nvgc, priority) + 1;
1727             xive2_nvgc_set_backlog(&nvgc, priority, backlog);
1728             xive2_router_write_nvgc(xrtr, crowd, nvx_blk, nvx_idx, &nvgc);
1729 
1730             if (backlog == 1) {
1731                 XiveFabricClass *xfc = XIVE_FABRIC_GET_CLASS(xrtr->xfb);
1732                 xfc->broadcast(xrtr->xfb, nvx_blk, nvx_idx,
1733                                crowd, cam_ignore, priority);
1734 
1735                 if (!xive2_end_is_precluded_escalation(&end)) {
1736                     /*
1737                      * The interrupt will be picked up when the
1738                      * matching thread lowers its priority level
1739                      */
1740                     return;
1741                 }
1742             }
1743         }
1744     }
1745 
1746 do_escalation:
1747     /*
1748      * If activated, escalate notification using the ESe PQ bits and
1749      * the EAS in w4-5
1750      */
1751     if (!xive2_end_is_escalate(&end)) {
1752         return;
1753     }
1754 
1755     /*
1756      * Check the END ESe (Event State Buffer for escalation) for even
1757      * further coalescing in the Router
1758      */
1759     if (!xive2_end_is_uncond_escalation(&end)) {
1760         /* ESe[Q]=1 : end of escalation notification */
1761         if (!xive2_router_end_es_notify(xrtr, end_blk, end_idx,
1762                                        &end, END2_W1_ESe)) {
1763             return;
1764         }
1765     }
1766 
1767     if (xive2_end_is_escalate_end(&end)) {
1768         /*
1769          * Perform END Adaptive escalation processing
1770          * The END trigger becomes an Escalation trigger
1771          */
1772         uint8_t esc_blk = xive_get_field32(END2_W4_END_BLOCK, end.w4);
1773         uint32_t esc_idx = xive_get_field32(END2_W4_ESC_END_INDEX, end.w4);
1774         uint32_t esc_data = xive_get_field32(END2_W5_ESC_END_DATA, end.w5);
1775         trace_xive_escalate_end(end_blk, end_idx, esc_blk, esc_idx, esc_data);
1776         xive2_router_end_notify(xrtr, esc_blk, esc_idx, esc_data, false);
1777     } /* end END adaptive escalation */
1778 
1779     else {
1780         uint32_t lisn;              /* Logical Interrupt Source Number */
1781 
1782         /*
1783          *  Perform ESB escalation processing
1784          *      E[N] == 1 --> N
1785          *      Req[Block] <- E[ESB_Block]
1786          *      Req[Index] <- E[ESB_Index]
1787          *      Req[Offset] <- 0x000
1788          *      Execute <ESB Store> Req command
1789          */
1790         lisn = XIVE_EAS(xive_get_field32(END2_W4_END_BLOCK,     end.w4),
1791                         xive_get_field32(END2_W4_ESC_END_INDEX, end.w4));
1792 
1793         trace_xive_escalate_esb(end_blk, end_idx, lisn);
1794         xive2_notify(xrtr, lisn, true /* pq_checked */);
1795     }
1796 
1797     return;
1798 }
1799 
1800 void xive2_notify(Xive2Router *xrtr , uint32_t lisn, bool pq_checked)
1801 {
1802     uint8_t eas_blk = XIVE_EAS_BLOCK(lisn);
1803     uint32_t eas_idx = XIVE_EAS_INDEX(lisn);
1804     Xive2Eas eas;
1805 
1806     /* EAS cache lookup */
1807     if (xive2_router_get_eas(xrtr, eas_blk, eas_idx, &eas)) {
1808         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: Unknown LISN %x\n", lisn);
1809         return;
1810     }
1811 
1812     if (!pq_checked) {
1813         bool notify;
1814         uint8_t pq;
1815 
1816         /* PQ cache lookup */
1817         if (xive2_router_get_pq(xrtr, eas_blk, eas_idx, &pq)) {
1818             /* Set FIR */
1819             g_assert_not_reached();
1820         }
1821 
1822         notify = xive_esb_trigger(&pq);
1823 
1824         if (xive2_router_set_pq(xrtr, eas_blk, eas_idx, &pq)) {
1825             /* Set FIR */
1826             g_assert_not_reached();
1827         }
1828 
1829         if (!notify) {
1830             return;
1831         }
1832     }
1833 
1834     if (!xive2_eas_is_valid(&eas)) {
1835         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: Invalid LISN %x\n", lisn);
1836         return;
1837     }
1838 
1839     if (xive2_eas_is_masked(&eas)) {
1840         /* Notification completed */
1841         return;
1842     }
1843 
1844     /* TODO: add support for EAS resume */
1845     if (xive2_eas_is_resume(&eas)) {
1846         qemu_log_mask(LOG_UNIMP,
1847                       "XIVE: EAS resume processing unimplemented - LISN %x\n",
1848                       lisn);
1849         return;
1850     }
1851 
1852     /*
1853      * The event trigger becomes an END trigger
1854      */
1855     xive2_router_end_notify(xrtr,
1856                             xive_get_field64(EAS2_END_BLOCK, eas.w),
1857                             xive_get_field64(EAS2_END_INDEX, eas.w),
1858                             xive_get_field64(EAS2_END_DATA,  eas.w),
1859                             false);
1860     return;
1861 }
1862 
1863 void xive2_router_notify(XiveNotifier *xn, uint32_t lisn, bool pq_checked)
1864 {
1865     Xive2Router *xrtr = XIVE2_ROUTER(xn);
1866 
1867     xive2_notify(xrtr, lisn, pq_checked);
1868     return;
1869 }
1870 
1871 static const Property xive2_router_properties[] = {
1872     DEFINE_PROP_LINK("xive-fabric", Xive2Router, xfb,
1873                      TYPE_XIVE_FABRIC, XiveFabric *),
1874 };
1875 
1876 static void xive2_router_class_init(ObjectClass *klass, const void *data)
1877 {
1878     DeviceClass *dc = DEVICE_CLASS(klass);
1879     XiveNotifierClass *xnc = XIVE_NOTIFIER_CLASS(klass);
1880 
1881     dc->desc    = "XIVE2 Router Engine";
1882     device_class_set_props(dc, xive2_router_properties);
1883     /* Parent is SysBusDeviceClass. No need to call its realize hook */
1884     dc->realize = xive2_router_realize;
1885     xnc->notify = xive2_router_notify;
1886 }
1887 
1888 static const TypeInfo xive2_router_info = {
1889     .name          = TYPE_XIVE2_ROUTER,
1890     .parent        = TYPE_SYS_BUS_DEVICE,
1891     .abstract      = true,
1892     .instance_size = sizeof(Xive2Router),
1893     .class_size    = sizeof(Xive2RouterClass),
1894     .class_init    = xive2_router_class_init,
1895     .interfaces    = (const InterfaceInfo[]) {
1896         { TYPE_XIVE_NOTIFIER },
1897         { TYPE_XIVE_PRESENTER },
1898         { }
1899     }
1900 };
1901 
1902 static inline bool addr_is_even(hwaddr addr, uint32_t shift)
1903 {
1904     return !((addr >> shift) & 1);
1905 }
1906 
1907 static uint64_t xive2_end_source_read(void *opaque, hwaddr addr, unsigned size)
1908 {
1909     Xive2EndSource *xsrc = XIVE2_END_SOURCE(opaque);
1910     uint32_t offset = addr & 0xFFF;
1911     uint8_t end_blk;
1912     uint32_t end_idx;
1913     Xive2End end;
1914     uint32_t end_esmask;
1915     uint8_t pq;
1916     uint64_t ret;
1917 
1918     /*
1919      * The block id should be deduced from the load address on the END
1920      * ESB MMIO but our model only supports a single block per XIVE chip.
1921      */
1922     end_blk = xive2_router_get_block_id(xsrc->xrtr);
1923     end_idx = addr >> (xsrc->esb_shift + 1);
1924 
1925     if (xive2_router_get_end(xsrc->xrtr, end_blk, end_idx, &end)) {
1926         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: No END %x/%x\n", end_blk,
1927                       end_idx);
1928         return -1;
1929     }
1930 
1931     if (!xive2_end_is_valid(&end)) {
1932         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: END %x/%x is invalid\n",
1933                       end_blk, end_idx);
1934         return -1;
1935     }
1936 
1937     end_esmask = addr_is_even(addr, xsrc->esb_shift) ? END2_W1_ESn :
1938         END2_W1_ESe;
1939     pq = xive_get_field32(end_esmask, end.w1);
1940 
1941     switch (offset) {
1942     case XIVE_ESB_LOAD_EOI ... XIVE_ESB_LOAD_EOI + 0x7FF:
1943         ret = xive_esb_eoi(&pq);
1944 
1945         /* Forward the source event notification for routing ?? */
1946         break;
1947 
1948     case XIVE_ESB_GET ... XIVE_ESB_GET + 0x3FF:
1949         ret = pq;
1950         break;
1951 
1952     case XIVE_ESB_SET_PQ_00 ... XIVE_ESB_SET_PQ_00 + 0x0FF:
1953     case XIVE_ESB_SET_PQ_01 ... XIVE_ESB_SET_PQ_01 + 0x0FF:
1954     case XIVE_ESB_SET_PQ_10 ... XIVE_ESB_SET_PQ_10 + 0x0FF:
1955     case XIVE_ESB_SET_PQ_11 ... XIVE_ESB_SET_PQ_11 + 0x0FF:
1956         ret = xive_esb_set(&pq, (offset >> 8) & 0x3);
1957         break;
1958     default:
1959         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: invalid END ESB load addr %d\n",
1960                       offset);
1961         return -1;
1962     }
1963 
1964     if (pq != xive_get_field32(end_esmask, end.w1)) {
1965         end.w1 = xive_set_field32(end_esmask, end.w1, pq);
1966         xive2_router_write_end(xsrc->xrtr, end_blk, end_idx, &end, 1);
1967     }
1968 
1969     return ret;
1970 }
1971 
1972 static void xive2_end_source_write(void *opaque, hwaddr addr,
1973                                    uint64_t value, unsigned size)
1974 {
1975     Xive2EndSource *xsrc = XIVE2_END_SOURCE(opaque);
1976     uint32_t offset = addr & 0xFFF;
1977     uint8_t end_blk;
1978     uint32_t end_idx;
1979     Xive2End end;
1980     uint32_t end_esmask;
1981     uint8_t pq;
1982     bool notify = false;
1983 
1984     /*
1985      * The block id should be deduced from the load address on the END
1986      * ESB MMIO but our model only supports a single block per XIVE chip.
1987      */
1988     end_blk = xive2_router_get_block_id(xsrc->xrtr);
1989     end_idx = addr >> (xsrc->esb_shift + 1);
1990 
1991     if (xive2_router_get_end(xsrc->xrtr, end_blk, end_idx, &end)) {
1992         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: No END %x/%x\n", end_blk,
1993                       end_idx);
1994         return;
1995     }
1996 
1997     if (!xive2_end_is_valid(&end)) {
1998         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: END %x/%x is invalid\n",
1999                       end_blk, end_idx);
2000         return;
2001     }
2002 
2003     end_esmask = addr_is_even(addr, xsrc->esb_shift) ? END2_W1_ESn :
2004         END2_W1_ESe;
2005     pq = xive_get_field32(end_esmask, end.w1);
2006 
2007     switch (offset) {
2008     case 0 ... 0x3FF:
2009         notify = xive_esb_trigger(&pq);
2010         break;
2011 
2012     case XIVE_ESB_STORE_EOI ... XIVE_ESB_STORE_EOI + 0x3FF:
2013         /* TODO: can we check StoreEOI availability from the router ? */
2014         notify = xive_esb_eoi(&pq);
2015         break;
2016 
2017     case XIVE_ESB_INJECT ... XIVE_ESB_INJECT + 0x3FF:
2018         if (end_esmask == END2_W1_ESe) {
2019             qemu_log_mask(LOG_GUEST_ERROR,
2020                           "XIVE: END %x/%x can not EQ inject on ESe\n",
2021                            end_blk, end_idx);
2022             return;
2023         }
2024         notify = true;
2025         break;
2026 
2027     default:
2028         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: invalid END ESB write addr %d\n",
2029                       offset);
2030         return;
2031     }
2032 
2033     if (pq != xive_get_field32(end_esmask, end.w1)) {
2034         end.w1 = xive_set_field32(end_esmask, end.w1, pq);
2035         xive2_router_write_end(xsrc->xrtr, end_blk, end_idx, &end, 1);
2036     }
2037 
2038     /* TODO: Forward the source event notification for routing */
2039     if (notify) {
2040         ;
2041     }
2042 }
2043 
2044 static const MemoryRegionOps xive2_end_source_ops = {
2045     .read = xive2_end_source_read,
2046     .write = xive2_end_source_write,
2047     .endianness = DEVICE_BIG_ENDIAN,
2048     .valid = {
2049         .min_access_size = 1,
2050         .max_access_size = 8,
2051     },
2052     .impl = {
2053         .min_access_size = 1,
2054         .max_access_size = 8,
2055     },
2056 };
2057 
2058 static void xive2_end_source_realize(DeviceState *dev, Error **errp)
2059 {
2060     Xive2EndSource *xsrc = XIVE2_END_SOURCE(dev);
2061 
2062     assert(xsrc->xrtr);
2063 
2064     if (!xsrc->nr_ends) {
2065         error_setg(errp, "Number of interrupt needs to be greater than 0");
2066         return;
2067     }
2068 
2069     if (xsrc->esb_shift != XIVE_ESB_4K &&
2070         xsrc->esb_shift != XIVE_ESB_64K) {
2071         error_setg(errp, "Invalid ESB shift setting");
2072         return;
2073     }
2074 
2075     /*
2076      * Each END is assigned an even/odd pair of MMIO pages, the even page
2077      * manages the ESn field while the odd page manages the ESe field.
2078      */
2079     memory_region_init_io(&xsrc->esb_mmio, OBJECT(xsrc),
2080                           &xive2_end_source_ops, xsrc, "xive.end",
2081                           (1ull << (xsrc->esb_shift + 1)) * xsrc->nr_ends);
2082 }
2083 
2084 static const Property xive2_end_source_properties[] = {
2085     DEFINE_PROP_UINT32("nr-ends", Xive2EndSource, nr_ends, 0),
2086     DEFINE_PROP_UINT32("shift", Xive2EndSource, esb_shift, XIVE_ESB_64K),
2087     DEFINE_PROP_LINK("xive", Xive2EndSource, xrtr, TYPE_XIVE2_ROUTER,
2088                      Xive2Router *),
2089 };
2090 
2091 static void xive2_end_source_class_init(ObjectClass *klass, const void *data)
2092 {
2093     DeviceClass *dc = DEVICE_CLASS(klass);
2094 
2095     dc->desc    = "XIVE END Source";
2096     device_class_set_props(dc, xive2_end_source_properties);
2097     dc->realize = xive2_end_source_realize;
2098     dc->user_creatable = false;
2099 }
2100 
2101 static const TypeInfo xive2_end_source_info = {
2102     .name          = TYPE_XIVE2_END_SOURCE,
2103     .parent        = TYPE_DEVICE,
2104     .instance_size = sizeof(Xive2EndSource),
2105     .class_init    = xive2_end_source_class_init,
2106 };
2107 
2108 static void xive2_register_types(void)
2109 {
2110     type_register_static(&xive2_router_info);
2111     type_register_static(&xive2_end_source_info);
2112 }
2113 
2114 type_init(xive2_register_types)
2115