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