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