xref: /openbmc/qemu/hw/intc/xive.c (revision 854f63d4)
1 /*
2  * QEMU PowerPC XIVE interrupt controller model
3  *
4  * Copyright (c) 2017-2018, IBM Corporation.
5  *
6  * This code is licensed under the GPL version 2 or later. See the
7  * COPYING file in the top-level directory.
8  */
9 
10 #include "qemu/osdep.h"
11 #include "qemu/log.h"
12 #include "qemu/module.h"
13 #include "qapi/error.h"
14 #include "target/ppc/cpu.h"
15 #include "sysemu/cpus.h"
16 #include "sysemu/dma.h"
17 #include "hw/qdev-properties.h"
18 #include "monitor/monitor.h"
19 #include "hw/ppc/xive.h"
20 #include "hw/ppc/xive_regs.h"
21 
22 /*
23  * XIVE Thread Interrupt Management context
24  */
25 
26 /*
27  * Convert a priority number to an Interrupt Pending Buffer (IPB)
28  * register, which indicates a pending interrupt at the priority
29  * corresponding to the bit number
30  */
31 static uint8_t priority_to_ipb(uint8_t priority)
32 {
33     return priority > XIVE_PRIORITY_MAX ?
34         0 : 1 << (XIVE_PRIORITY_MAX - priority);
35 }
36 
37 /*
38  * Convert an Interrupt Pending Buffer (IPB) register to a Pending
39  * Interrupt Priority Register (PIPR), which contains the priority of
40  * the most favored pending notification.
41  */
42 static uint8_t ipb_to_pipr(uint8_t ibp)
43 {
44     return ibp ? clz32((uint32_t)ibp << 24) : 0xff;
45 }
46 
47 static void ipb_update(uint8_t *regs, uint8_t priority)
48 {
49     regs[TM_IPB] |= priority_to_ipb(priority);
50     regs[TM_PIPR] = ipb_to_pipr(regs[TM_IPB]);
51 }
52 
53 static uint8_t exception_mask(uint8_t ring)
54 {
55     switch (ring) {
56     case TM_QW1_OS:
57         return TM_QW1_NSR_EO;
58     case TM_QW3_HV_PHYS:
59         return TM_QW3_NSR_HE;
60     default:
61         g_assert_not_reached();
62     }
63 }
64 
65 static qemu_irq xive_tctx_output(XiveTCTX *tctx, uint8_t ring)
66 {
67         switch (ring) {
68         case TM_QW0_USER:
69                 return 0; /* Not supported */
70         case TM_QW1_OS:
71                 return tctx->os_output;
72         case TM_QW2_HV_POOL:
73         case TM_QW3_HV_PHYS:
74                 return tctx->hv_output;
75         default:
76                 return 0;
77         }
78 }
79 
80 static uint64_t xive_tctx_accept(XiveTCTX *tctx, uint8_t ring)
81 {
82     uint8_t *regs = &tctx->regs[ring];
83     uint8_t nsr = regs[TM_NSR];
84     uint8_t mask = exception_mask(ring);
85 
86     qemu_irq_lower(xive_tctx_output(tctx, ring));
87 
88     if (regs[TM_NSR] & mask) {
89         uint8_t cppr = regs[TM_PIPR];
90 
91         regs[TM_CPPR] = cppr;
92 
93         /* Reset the pending buffer bit */
94         regs[TM_IPB] &= ~priority_to_ipb(cppr);
95         regs[TM_PIPR] = ipb_to_pipr(regs[TM_IPB]);
96 
97         /* Drop Exception bit */
98         regs[TM_NSR] &= ~mask;
99     }
100 
101     return (nsr << 8) | regs[TM_CPPR];
102 }
103 
104 static void xive_tctx_notify(XiveTCTX *tctx, uint8_t ring)
105 {
106     uint8_t *regs = &tctx->regs[ring];
107 
108     if (regs[TM_PIPR] < regs[TM_CPPR]) {
109         switch (ring) {
110         case TM_QW1_OS:
111             regs[TM_NSR] |= TM_QW1_NSR_EO;
112             break;
113         case TM_QW3_HV_PHYS:
114             regs[TM_NSR] |= (TM_QW3_NSR_HE_PHYS << 6);
115             break;
116         default:
117             g_assert_not_reached();
118         }
119         qemu_irq_raise(xive_tctx_output(tctx, ring));
120     }
121 }
122 
123 static void xive_tctx_set_cppr(XiveTCTX *tctx, uint8_t ring, uint8_t cppr)
124 {
125     if (cppr > XIVE_PRIORITY_MAX) {
126         cppr = 0xff;
127     }
128 
129     tctx->regs[ring + TM_CPPR] = cppr;
130 
131     /* CPPR has changed, check if we need to raise a pending exception */
132     xive_tctx_notify(tctx, ring);
133 }
134 
135 /*
136  * XIVE Thread Interrupt Management Area (TIMA)
137  */
138 
139 static void xive_tm_set_hv_cppr(XiveTCTX *tctx, hwaddr offset,
140                                 uint64_t value, unsigned size)
141 {
142     xive_tctx_set_cppr(tctx, TM_QW3_HV_PHYS, value & 0xff);
143 }
144 
145 static uint64_t xive_tm_ack_hv_reg(XiveTCTX *tctx, hwaddr offset, unsigned size)
146 {
147     return xive_tctx_accept(tctx, TM_QW3_HV_PHYS);
148 }
149 
150 static uint64_t xive_tm_pull_pool_ctx(XiveTCTX *tctx, hwaddr offset,
151                                       unsigned size)
152 {
153     uint64_t ret;
154 
155     ret = tctx->regs[TM_QW2_HV_POOL + TM_WORD2] & TM_QW2W2_POOL_CAM;
156     tctx->regs[TM_QW2_HV_POOL + TM_WORD2] &= ~TM_QW2W2_POOL_CAM;
157     return ret;
158 }
159 
160 static void xive_tm_vt_push(XiveTCTX *tctx, hwaddr offset,
161                             uint64_t value, unsigned size)
162 {
163     tctx->regs[TM_QW3_HV_PHYS + TM_WORD2] = value & 0xff;
164 }
165 
166 static uint64_t xive_tm_vt_poll(XiveTCTX *tctx, hwaddr offset, unsigned size)
167 {
168     return tctx->regs[TM_QW3_HV_PHYS + TM_WORD2] & 0xff;
169 }
170 
171 /*
172  * Define an access map for each page of the TIMA that we will use in
173  * the memory region ops to filter values when doing loads and stores
174  * of raw registers values
175  *
176  * Registers accessibility bits :
177  *
178  *    0x0 - no access
179  *    0x1 - write only
180  *    0x2 - read only
181  *    0x3 - read/write
182  */
183 
184 static const uint8_t xive_tm_hw_view[] = {
185     /* QW-0 User */   3, 0, 0, 0,   0, 0, 0, 0,   3, 3, 3, 3,   0, 0, 0, 0,
186     /* QW-1 OS   */   3, 3, 3, 3,   3, 3, 0, 3,   3, 3, 3, 3,   0, 0, 0, 0,
187     /* QW-2 POOL */   0, 0, 3, 3,   0, 0, 0, 0,   3, 3, 3, 3,   0, 0, 0, 0,
188     /* QW-3 PHYS */   3, 3, 3, 3,   0, 3, 0, 3,   3, 0, 0, 3,   3, 3, 3, 0,
189 };
190 
191 static const uint8_t xive_tm_hv_view[] = {
192     /* QW-0 User */   3, 0, 0, 0,   0, 0, 0, 0,   3, 3, 3, 3,   0, 0, 0, 0,
193     /* QW-1 OS   */   3, 3, 3, 3,   3, 3, 0, 3,   3, 3, 3, 3,   0, 0, 0, 0,
194     /* QW-2 POOL */   0, 0, 3, 3,   0, 0, 0, 0,   0, 3, 3, 3,   0, 0, 0, 0,
195     /* QW-3 PHYS */   3, 3, 3, 3,   0, 3, 0, 3,   3, 0, 0, 3,   0, 0, 0, 0,
196 };
197 
198 static const uint8_t xive_tm_os_view[] = {
199     /* QW-0 User */   3, 0, 0, 0,   0, 0, 0, 0,   3, 3, 3, 3,   0, 0, 0, 0,
200     /* QW-1 OS   */   2, 3, 2, 2,   2, 2, 0, 2,   0, 0, 0, 0,   0, 0, 0, 0,
201     /* QW-2 POOL */   0, 0, 0, 0,   0, 0, 0, 0,   0, 0, 0, 0,   0, 0, 0, 0,
202     /* QW-3 PHYS */   0, 0, 0, 0,   0, 0, 0, 0,   0, 0, 0, 0,   0, 0, 0, 0,
203 };
204 
205 static const uint8_t xive_tm_user_view[] = {
206     /* QW-0 User */   3, 0, 0, 0,   0, 0, 0, 0,   0, 0, 0, 0,   0, 0, 0, 0,
207     /* QW-1 OS   */   0, 0, 0, 0,   0, 0, 0, 0,   0, 0, 0, 0,   0, 0, 0, 0,
208     /* QW-2 POOL */   0, 0, 0, 0,   0, 0, 0, 0,   0, 0, 0, 0,   0, 0, 0, 0,
209     /* QW-3 PHYS */   0, 0, 0, 0,   0, 0, 0, 0,   0, 0, 0, 0,   0, 0, 0, 0,
210 };
211 
212 /*
213  * Overall TIMA access map for the thread interrupt management context
214  * registers
215  */
216 static const uint8_t *xive_tm_views[] = {
217     [XIVE_TM_HW_PAGE]   = xive_tm_hw_view,
218     [XIVE_TM_HV_PAGE]   = xive_tm_hv_view,
219     [XIVE_TM_OS_PAGE]   = xive_tm_os_view,
220     [XIVE_TM_USER_PAGE] = xive_tm_user_view,
221 };
222 
223 /*
224  * Computes a register access mask for a given offset in the TIMA
225  */
226 static uint64_t xive_tm_mask(hwaddr offset, unsigned size, bool write)
227 {
228     uint8_t page_offset = (offset >> TM_SHIFT) & 0x3;
229     uint8_t reg_offset = offset & 0x3F;
230     uint8_t reg_mask = write ? 0x1 : 0x2;
231     uint64_t mask = 0x0;
232     int i;
233 
234     for (i = 0; i < size; i++) {
235         if (xive_tm_views[page_offset][reg_offset + i] & reg_mask) {
236             mask |= (uint64_t) 0xff << (8 * (size - i - 1));
237         }
238     }
239 
240     return mask;
241 }
242 
243 static void xive_tm_raw_write(XiveTCTX *tctx, hwaddr offset, uint64_t value,
244                               unsigned size)
245 {
246     uint8_t ring_offset = offset & 0x30;
247     uint8_t reg_offset = offset & 0x3F;
248     uint64_t mask = xive_tm_mask(offset, size, true);
249     int i;
250 
251     /*
252      * Only 4 or 8 bytes stores are allowed and the User ring is
253      * excluded
254      */
255     if (size < 4 || !mask || ring_offset == TM_QW0_USER) {
256         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: invalid write access at TIMA @%"
257                       HWADDR_PRIx"\n", offset);
258         return;
259     }
260 
261     /*
262      * Use the register offset for the raw values and filter out
263      * reserved values
264      */
265     for (i = 0; i < size; i++) {
266         uint8_t byte_mask = (mask >> (8 * (size - i - 1)));
267         if (byte_mask) {
268             tctx->regs[reg_offset + i] = (value >> (8 * (size - i - 1))) &
269                 byte_mask;
270         }
271     }
272 }
273 
274 static uint64_t xive_tm_raw_read(XiveTCTX *tctx, hwaddr offset, unsigned size)
275 {
276     uint8_t ring_offset = offset & 0x30;
277     uint8_t reg_offset = offset & 0x3F;
278     uint64_t mask = xive_tm_mask(offset, size, false);
279     uint64_t ret;
280     int i;
281 
282     /*
283      * Only 4 or 8 bytes loads are allowed and the User ring is
284      * excluded
285      */
286     if (size < 4 || !mask || ring_offset == TM_QW0_USER) {
287         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: invalid read access at TIMA @%"
288                       HWADDR_PRIx"\n", offset);
289         return -1;
290     }
291 
292     /* Use the register offset for the raw values */
293     ret = 0;
294     for (i = 0; i < size; i++) {
295         ret |= (uint64_t) tctx->regs[reg_offset + i] << (8 * (size - i - 1));
296     }
297 
298     /* filter out reserved values */
299     return ret & mask;
300 }
301 
302 /*
303  * The TM context is mapped twice within each page. Stores and loads
304  * to the first mapping below 2K write and read the specified values
305  * without modification. The second mapping above 2K performs specific
306  * state changes (side effects) in addition to setting/returning the
307  * interrupt management area context of the processor thread.
308  */
309 static uint64_t xive_tm_ack_os_reg(XiveTCTX *tctx, hwaddr offset, unsigned size)
310 {
311     return xive_tctx_accept(tctx, TM_QW1_OS);
312 }
313 
314 static void xive_tm_set_os_cppr(XiveTCTX *tctx, hwaddr offset,
315                                 uint64_t value, unsigned size)
316 {
317     xive_tctx_set_cppr(tctx, TM_QW1_OS, value & 0xff);
318 }
319 
320 /*
321  * Adjust the IPB to allow a CPU to process event queues of other
322  * priorities during one physical interrupt cycle.
323  */
324 static void xive_tm_set_os_pending(XiveTCTX *tctx, hwaddr offset,
325                                    uint64_t value, unsigned size)
326 {
327     ipb_update(&tctx->regs[TM_QW1_OS], value & 0xff);
328     xive_tctx_notify(tctx, TM_QW1_OS);
329 }
330 
331 /*
332  * Define a mapping of "special" operations depending on the TIMA page
333  * offset and the size of the operation.
334  */
335 typedef struct XiveTmOp {
336     uint8_t  page_offset;
337     uint32_t op_offset;
338     unsigned size;
339     void     (*write_handler)(XiveTCTX *tctx, hwaddr offset, uint64_t value,
340                               unsigned size);
341     uint64_t (*read_handler)(XiveTCTX *tctx, hwaddr offset, unsigned size);
342 } XiveTmOp;
343 
344 static const XiveTmOp xive_tm_operations[] = {
345     /*
346      * MMIOs below 2K : raw values and special operations without side
347      * effects
348      */
349     { XIVE_TM_OS_PAGE, TM_QW1_OS + TM_CPPR,   1, xive_tm_set_os_cppr, NULL },
350     { XIVE_TM_HV_PAGE, TM_QW3_HV_PHYS + TM_CPPR, 1, xive_tm_set_hv_cppr, NULL },
351     { XIVE_TM_HV_PAGE, TM_QW3_HV_PHYS + TM_WORD2, 1, xive_tm_vt_push, NULL },
352     { XIVE_TM_HV_PAGE, TM_QW3_HV_PHYS + TM_WORD2, 1, NULL, xive_tm_vt_poll },
353 
354     /* MMIOs above 2K : special operations with side effects */
355     { XIVE_TM_OS_PAGE, TM_SPC_ACK_OS_REG,     2, NULL, xive_tm_ack_os_reg },
356     { XIVE_TM_OS_PAGE, TM_SPC_SET_OS_PENDING, 1, xive_tm_set_os_pending, NULL },
357     { XIVE_TM_HV_PAGE, TM_SPC_ACK_HV_REG,     2, NULL, xive_tm_ack_hv_reg },
358     { XIVE_TM_HV_PAGE, TM_SPC_PULL_POOL_CTX,  4, NULL, xive_tm_pull_pool_ctx },
359     { XIVE_TM_HV_PAGE, TM_SPC_PULL_POOL_CTX,  8, NULL, xive_tm_pull_pool_ctx },
360 };
361 
362 static const XiveTmOp *xive_tm_find_op(hwaddr offset, unsigned size, bool write)
363 {
364     uint8_t page_offset = (offset >> TM_SHIFT) & 0x3;
365     uint32_t op_offset = offset & 0xFFF;
366     int i;
367 
368     for (i = 0; i < ARRAY_SIZE(xive_tm_operations); i++) {
369         const XiveTmOp *xto = &xive_tm_operations[i];
370 
371         /* Accesses done from a more privileged TIMA page is allowed */
372         if (xto->page_offset >= page_offset &&
373             xto->op_offset == op_offset &&
374             xto->size == size &&
375             ((write && xto->write_handler) || (!write && xto->read_handler))) {
376             return xto;
377         }
378     }
379     return NULL;
380 }
381 
382 /*
383  * TIMA MMIO handlers
384  */
385 void xive_tctx_tm_write(XiveTCTX *tctx, hwaddr offset, uint64_t value,
386                         unsigned size)
387 {
388     const XiveTmOp *xto;
389 
390     /*
391      * TODO: check V bit in Q[0-3]W2
392      */
393 
394     /*
395      * First, check for special operations in the 2K region
396      */
397     if (offset & 0x800) {
398         xto = xive_tm_find_op(offset, size, true);
399         if (!xto) {
400             qemu_log_mask(LOG_GUEST_ERROR, "XIVE: invalid write access at TIMA"
401                           "@%"HWADDR_PRIx"\n", offset);
402         } else {
403             xto->write_handler(tctx, offset, value, size);
404         }
405         return;
406     }
407 
408     /*
409      * Then, for special operations in the region below 2K.
410      */
411     xto = xive_tm_find_op(offset, size, true);
412     if (xto) {
413         xto->write_handler(tctx, offset, value, size);
414         return;
415     }
416 
417     /*
418      * Finish with raw access to the register values
419      */
420     xive_tm_raw_write(tctx, offset, value, size);
421 }
422 
423 uint64_t xive_tctx_tm_read(XiveTCTX *tctx, hwaddr offset, unsigned size)
424 {
425     const XiveTmOp *xto;
426 
427     /*
428      * TODO: check V bit in Q[0-3]W2
429      */
430 
431     /*
432      * First, check for special operations in the 2K region
433      */
434     if (offset & 0x800) {
435         xto = xive_tm_find_op(offset, size, false);
436         if (!xto) {
437             qemu_log_mask(LOG_GUEST_ERROR, "XIVE: invalid read access to TIMA"
438                           "@%"HWADDR_PRIx"\n", offset);
439             return -1;
440         }
441         return xto->read_handler(tctx, offset, size);
442     }
443 
444     /*
445      * Then, for special operations in the region below 2K.
446      */
447     xto = xive_tm_find_op(offset, size, false);
448     if (xto) {
449         return xto->read_handler(tctx, offset, size);
450     }
451 
452     /*
453      * Finish with raw access to the register values
454      */
455     return xive_tm_raw_read(tctx, offset, size);
456 }
457 
458 static void xive_tm_write(void *opaque, hwaddr offset,
459                           uint64_t value, unsigned size)
460 {
461     XiveTCTX *tctx = xive_router_get_tctx(XIVE_ROUTER(opaque), current_cpu);
462 
463     xive_tctx_tm_write(tctx, offset, value, size);
464 }
465 
466 static uint64_t xive_tm_read(void *opaque, hwaddr offset, unsigned size)
467 {
468     XiveTCTX *tctx = xive_router_get_tctx(XIVE_ROUTER(opaque), current_cpu);
469 
470     return xive_tctx_tm_read(tctx, offset, size);
471 }
472 
473 const MemoryRegionOps xive_tm_ops = {
474     .read = xive_tm_read,
475     .write = xive_tm_write,
476     .endianness = DEVICE_BIG_ENDIAN,
477     .valid = {
478         .min_access_size = 1,
479         .max_access_size = 8,
480     },
481     .impl = {
482         .min_access_size = 1,
483         .max_access_size = 8,
484     },
485 };
486 
487 static inline uint32_t xive_tctx_word2(uint8_t *ring)
488 {
489     return *((uint32_t *) &ring[TM_WORD2]);
490 }
491 
492 static char *xive_tctx_ring_print(uint8_t *ring)
493 {
494     uint32_t w2 = xive_tctx_word2(ring);
495 
496     return g_strdup_printf("%02x   %02x  %02x    %02x   %02x  "
497                    "%02x  %02x   %02x  %08x",
498                    ring[TM_NSR], ring[TM_CPPR], ring[TM_IPB], ring[TM_LSMFB],
499                    ring[TM_ACK_CNT], ring[TM_INC], ring[TM_AGE], ring[TM_PIPR],
500                    be32_to_cpu(w2));
501 }
502 
503 static const char * const xive_tctx_ring_names[] = {
504     "USER", "OS", "POOL", "PHYS",
505 };
506 
507 void xive_tctx_pic_print_info(XiveTCTX *tctx, Monitor *mon)
508 {
509     int cpu_index = tctx->cs ? tctx->cs->cpu_index : -1;
510     int i;
511 
512     if (kvm_irqchip_in_kernel()) {
513         Error *local_err = NULL;
514 
515         kvmppc_xive_cpu_synchronize_state(tctx, &local_err);
516         if (local_err) {
517             error_report_err(local_err);
518             return;
519         }
520     }
521 
522     monitor_printf(mon, "CPU[%04x]:   QW   NSR CPPR IPB LSMFB ACK# INC AGE PIPR"
523                    "  W2\n", cpu_index);
524 
525     for (i = 0; i < XIVE_TM_RING_COUNT; i++) {
526         char *s = xive_tctx_ring_print(&tctx->regs[i * XIVE_TM_RING_SIZE]);
527         monitor_printf(mon, "CPU[%04x]: %4s    %s\n", cpu_index,
528                        xive_tctx_ring_names[i], s);
529         g_free(s);
530     }
531 }
532 
533 static void xive_tctx_reset(void *dev)
534 {
535     XiveTCTX *tctx = XIVE_TCTX(dev);
536 
537     memset(tctx->regs, 0, sizeof(tctx->regs));
538 
539     /* Set some defaults */
540     tctx->regs[TM_QW1_OS + TM_LSMFB] = 0xFF;
541     tctx->regs[TM_QW1_OS + TM_ACK_CNT] = 0xFF;
542     tctx->regs[TM_QW1_OS + TM_AGE] = 0xFF;
543 
544     /*
545      * Initialize PIPR to 0xFF to avoid phantom interrupts when the
546      * CPPR is first set.
547      */
548     tctx->regs[TM_QW1_OS + TM_PIPR] =
549         ipb_to_pipr(tctx->regs[TM_QW1_OS + TM_IPB]);
550     tctx->regs[TM_QW3_HV_PHYS + TM_PIPR] =
551         ipb_to_pipr(tctx->regs[TM_QW3_HV_PHYS + TM_IPB]);
552 }
553 
554 static void xive_tctx_realize(DeviceState *dev, Error **errp)
555 {
556     XiveTCTX *tctx = XIVE_TCTX(dev);
557     PowerPCCPU *cpu;
558     CPUPPCState *env;
559     Object *obj;
560     Error *local_err = NULL;
561 
562     obj = object_property_get_link(OBJECT(dev), "cpu", &local_err);
563     if (!obj) {
564         error_propagate(errp, local_err);
565         error_prepend(errp, "required link 'cpu' not found: ");
566         return;
567     }
568 
569     cpu = POWERPC_CPU(obj);
570     tctx->cs = CPU(obj);
571 
572     env = &cpu->env;
573     switch (PPC_INPUT(env)) {
574     case PPC_FLAGS_INPUT_POWER9:
575         tctx->hv_output = env->irq_inputs[POWER9_INPUT_HINT];
576         tctx->os_output = env->irq_inputs[POWER9_INPUT_INT];
577         break;
578 
579     default:
580         error_setg(errp, "XIVE interrupt controller does not support "
581                    "this CPU bus model");
582         return;
583     }
584 
585     /* Connect the presenter to the VCPU (required for CPU hotplug) */
586     if (kvm_irqchip_in_kernel()) {
587         kvmppc_xive_cpu_connect(tctx, &local_err);
588         if (local_err) {
589             error_propagate(errp, local_err);
590             return;
591         }
592     }
593 
594     qemu_register_reset(xive_tctx_reset, dev);
595 }
596 
597 static void xive_tctx_unrealize(DeviceState *dev, Error **errp)
598 {
599     qemu_unregister_reset(xive_tctx_reset, dev);
600 }
601 
602 static int vmstate_xive_tctx_pre_save(void *opaque)
603 {
604     Error *local_err = NULL;
605 
606     if (kvm_irqchip_in_kernel()) {
607         kvmppc_xive_cpu_get_state(XIVE_TCTX(opaque), &local_err);
608         if (local_err) {
609             error_report_err(local_err);
610             return -1;
611         }
612     }
613 
614     return 0;
615 }
616 
617 static const VMStateDescription vmstate_xive_tctx = {
618     .name = TYPE_XIVE_TCTX,
619     .version_id = 1,
620     .minimum_version_id = 1,
621     .pre_save = vmstate_xive_tctx_pre_save,
622     .post_load = NULL, /* handled by the sPAPRxive model */
623     .fields = (VMStateField[]) {
624         VMSTATE_BUFFER(regs, XiveTCTX),
625         VMSTATE_END_OF_LIST()
626     },
627 };
628 
629 static void xive_tctx_class_init(ObjectClass *klass, void *data)
630 {
631     DeviceClass *dc = DEVICE_CLASS(klass);
632 
633     dc->desc = "XIVE Interrupt Thread Context";
634     dc->realize = xive_tctx_realize;
635     dc->unrealize = xive_tctx_unrealize;
636     dc->vmsd = &vmstate_xive_tctx;
637 }
638 
639 static const TypeInfo xive_tctx_info = {
640     .name          = TYPE_XIVE_TCTX,
641     .parent        = TYPE_DEVICE,
642     .instance_size = sizeof(XiveTCTX),
643     .class_init    = xive_tctx_class_init,
644 };
645 
646 Object *xive_tctx_create(Object *cpu, XiveRouter *xrtr, Error **errp)
647 {
648     Error *local_err = NULL;
649     Object *obj;
650 
651     obj = object_new(TYPE_XIVE_TCTX);
652     object_property_add_child(cpu, TYPE_XIVE_TCTX, obj, &error_abort);
653     object_unref(obj);
654     object_property_add_const_link(obj, "cpu", cpu, &error_abort);
655     object_property_set_bool(obj, true, "realized", &local_err);
656     if (local_err) {
657         goto error;
658     }
659 
660     return obj;
661 
662 error:
663     object_unparent(obj);
664     error_propagate(errp, local_err);
665     return NULL;
666 }
667 
668 /*
669  * XIVE ESB helpers
670  */
671 
672 static uint8_t xive_esb_set(uint8_t *pq, uint8_t value)
673 {
674     uint8_t old_pq = *pq & 0x3;
675 
676     *pq &= ~0x3;
677     *pq |= value & 0x3;
678 
679     return old_pq;
680 }
681 
682 static bool xive_esb_trigger(uint8_t *pq)
683 {
684     uint8_t old_pq = *pq & 0x3;
685 
686     switch (old_pq) {
687     case XIVE_ESB_RESET:
688         xive_esb_set(pq, XIVE_ESB_PENDING);
689         return true;
690     case XIVE_ESB_PENDING:
691     case XIVE_ESB_QUEUED:
692         xive_esb_set(pq, XIVE_ESB_QUEUED);
693         return false;
694     case XIVE_ESB_OFF:
695         xive_esb_set(pq, XIVE_ESB_OFF);
696         return false;
697     default:
698          g_assert_not_reached();
699     }
700 }
701 
702 static bool xive_esb_eoi(uint8_t *pq)
703 {
704     uint8_t old_pq = *pq & 0x3;
705 
706     switch (old_pq) {
707     case XIVE_ESB_RESET:
708     case XIVE_ESB_PENDING:
709         xive_esb_set(pq, XIVE_ESB_RESET);
710         return false;
711     case XIVE_ESB_QUEUED:
712         xive_esb_set(pq, XIVE_ESB_PENDING);
713         return true;
714     case XIVE_ESB_OFF:
715         xive_esb_set(pq, XIVE_ESB_OFF);
716         return false;
717     default:
718          g_assert_not_reached();
719     }
720 }
721 
722 /*
723  * XIVE Interrupt Source (or IVSE)
724  */
725 
726 uint8_t xive_source_esb_get(XiveSource *xsrc, uint32_t srcno)
727 {
728     assert(srcno < xsrc->nr_irqs);
729 
730     return xsrc->status[srcno] & 0x3;
731 }
732 
733 uint8_t xive_source_esb_set(XiveSource *xsrc, uint32_t srcno, uint8_t pq)
734 {
735     assert(srcno < xsrc->nr_irqs);
736 
737     return xive_esb_set(&xsrc->status[srcno], pq);
738 }
739 
740 /*
741  * Returns whether the event notification should be forwarded.
742  */
743 static bool xive_source_lsi_trigger(XiveSource *xsrc, uint32_t srcno)
744 {
745     uint8_t old_pq = xive_source_esb_get(xsrc, srcno);
746 
747     xsrc->status[srcno] |= XIVE_STATUS_ASSERTED;
748 
749     switch (old_pq) {
750     case XIVE_ESB_RESET:
751         xive_source_esb_set(xsrc, srcno, XIVE_ESB_PENDING);
752         return true;
753     default:
754         return false;
755     }
756 }
757 
758 /*
759  * Returns whether the event notification should be forwarded.
760  */
761 static bool xive_source_esb_trigger(XiveSource *xsrc, uint32_t srcno)
762 {
763     bool ret;
764 
765     assert(srcno < xsrc->nr_irqs);
766 
767     ret = xive_esb_trigger(&xsrc->status[srcno]);
768 
769     if (xive_source_irq_is_lsi(xsrc, srcno) &&
770         xive_source_esb_get(xsrc, srcno) == XIVE_ESB_QUEUED) {
771         qemu_log_mask(LOG_GUEST_ERROR,
772                       "XIVE: queued an event on LSI IRQ %d\n", srcno);
773     }
774 
775     return ret;
776 }
777 
778 /*
779  * Returns whether the event notification should be forwarded.
780  */
781 static bool xive_source_esb_eoi(XiveSource *xsrc, uint32_t srcno)
782 {
783     bool ret;
784 
785     assert(srcno < xsrc->nr_irqs);
786 
787     ret = xive_esb_eoi(&xsrc->status[srcno]);
788 
789     /*
790      * LSI sources do not set the Q bit but they can still be
791      * asserted, in which case we should forward a new event
792      * notification
793      */
794     if (xive_source_irq_is_lsi(xsrc, srcno) &&
795         xsrc->status[srcno] & XIVE_STATUS_ASSERTED) {
796         ret = xive_source_lsi_trigger(xsrc, srcno);
797     }
798 
799     return ret;
800 }
801 
802 /*
803  * Forward the source event notification to the Router
804  */
805 static void xive_source_notify(XiveSource *xsrc, int srcno)
806 {
807     XiveNotifierClass *xnc = XIVE_NOTIFIER_GET_CLASS(xsrc->xive);
808 
809     if (xnc->notify) {
810         xnc->notify(xsrc->xive, srcno);
811     }
812 }
813 
814 /*
815  * In a two pages ESB MMIO setting, even page is the trigger page, odd
816  * page is for management
817  */
818 static inline bool addr_is_even(hwaddr addr, uint32_t shift)
819 {
820     return !((addr >> shift) & 1);
821 }
822 
823 static inline bool xive_source_is_trigger_page(XiveSource *xsrc, hwaddr addr)
824 {
825     return xive_source_esb_has_2page(xsrc) &&
826         addr_is_even(addr, xsrc->esb_shift - 1);
827 }
828 
829 /*
830  * ESB MMIO loads
831  *                      Trigger page    Management/EOI page
832  *
833  * ESB MMIO setting     2 pages         1 or 2 pages
834  *
835  * 0x000 .. 0x3FF       -1              EOI and return 0|1
836  * 0x400 .. 0x7FF       -1              EOI and return 0|1
837  * 0x800 .. 0xBFF       -1              return PQ
838  * 0xC00 .. 0xCFF       -1              return PQ and atomically PQ=00
839  * 0xD00 .. 0xDFF       -1              return PQ and atomically PQ=01
840  * 0xE00 .. 0xDFF       -1              return PQ and atomically PQ=10
841  * 0xF00 .. 0xDFF       -1              return PQ and atomically PQ=11
842  */
843 static uint64_t xive_source_esb_read(void *opaque, hwaddr addr, unsigned size)
844 {
845     XiveSource *xsrc = XIVE_SOURCE(opaque);
846     uint32_t offset = addr & 0xFFF;
847     uint32_t srcno = addr >> xsrc->esb_shift;
848     uint64_t ret = -1;
849 
850     /* In a two pages ESB MMIO setting, trigger page should not be read */
851     if (xive_source_is_trigger_page(xsrc, addr)) {
852         qemu_log_mask(LOG_GUEST_ERROR,
853                       "XIVE: invalid load on IRQ %d trigger page at "
854                       "0x%"HWADDR_PRIx"\n", srcno, addr);
855         return -1;
856     }
857 
858     switch (offset) {
859     case XIVE_ESB_LOAD_EOI ... XIVE_ESB_LOAD_EOI + 0x7FF:
860         ret = xive_source_esb_eoi(xsrc, srcno);
861 
862         /* Forward the source event notification for routing */
863         if (ret) {
864             xive_source_notify(xsrc, srcno);
865         }
866         break;
867 
868     case XIVE_ESB_GET ... XIVE_ESB_GET + 0x3FF:
869         ret = xive_source_esb_get(xsrc, srcno);
870         break;
871 
872     case XIVE_ESB_SET_PQ_00 ... XIVE_ESB_SET_PQ_00 + 0x0FF:
873     case XIVE_ESB_SET_PQ_01 ... XIVE_ESB_SET_PQ_01 + 0x0FF:
874     case XIVE_ESB_SET_PQ_10 ... XIVE_ESB_SET_PQ_10 + 0x0FF:
875     case XIVE_ESB_SET_PQ_11 ... XIVE_ESB_SET_PQ_11 + 0x0FF:
876         ret = xive_source_esb_set(xsrc, srcno, (offset >> 8) & 0x3);
877         break;
878     default:
879         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: invalid ESB load addr %x\n",
880                       offset);
881     }
882 
883     return ret;
884 }
885 
886 /*
887  * ESB MMIO stores
888  *                      Trigger page    Management/EOI page
889  *
890  * ESB MMIO setting     2 pages         1 or 2 pages
891  *
892  * 0x000 .. 0x3FF       Trigger         Trigger
893  * 0x400 .. 0x7FF       Trigger         EOI
894  * 0x800 .. 0xBFF       Trigger         undefined
895  * 0xC00 .. 0xCFF       Trigger         PQ=00
896  * 0xD00 .. 0xDFF       Trigger         PQ=01
897  * 0xE00 .. 0xDFF       Trigger         PQ=10
898  * 0xF00 .. 0xDFF       Trigger         PQ=11
899  */
900 static void xive_source_esb_write(void *opaque, hwaddr addr,
901                                   uint64_t value, unsigned size)
902 {
903     XiveSource *xsrc = XIVE_SOURCE(opaque);
904     uint32_t offset = addr & 0xFFF;
905     uint32_t srcno = addr >> xsrc->esb_shift;
906     bool notify = false;
907 
908     /* In a two pages ESB MMIO setting, trigger page only triggers */
909     if (xive_source_is_trigger_page(xsrc, addr)) {
910         notify = xive_source_esb_trigger(xsrc, srcno);
911         goto out;
912     }
913 
914     switch (offset) {
915     case 0 ... 0x3FF:
916         notify = xive_source_esb_trigger(xsrc, srcno);
917         break;
918 
919     case XIVE_ESB_STORE_EOI ... XIVE_ESB_STORE_EOI + 0x3FF:
920         if (!(xsrc->esb_flags & XIVE_SRC_STORE_EOI)) {
921             qemu_log_mask(LOG_GUEST_ERROR,
922                           "XIVE: invalid Store EOI for IRQ %d\n", srcno);
923             return;
924         }
925 
926         notify = xive_source_esb_eoi(xsrc, srcno);
927         break;
928 
929     case XIVE_ESB_SET_PQ_00 ... XIVE_ESB_SET_PQ_00 + 0x0FF:
930     case XIVE_ESB_SET_PQ_01 ... XIVE_ESB_SET_PQ_01 + 0x0FF:
931     case XIVE_ESB_SET_PQ_10 ... XIVE_ESB_SET_PQ_10 + 0x0FF:
932     case XIVE_ESB_SET_PQ_11 ... XIVE_ESB_SET_PQ_11 + 0x0FF:
933         xive_source_esb_set(xsrc, srcno, (offset >> 8) & 0x3);
934         break;
935 
936     default:
937         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: invalid ESB write addr %x\n",
938                       offset);
939         return;
940     }
941 
942 out:
943     /* Forward the source event notification for routing */
944     if (notify) {
945         xive_source_notify(xsrc, srcno);
946     }
947 }
948 
949 static const MemoryRegionOps xive_source_esb_ops = {
950     .read = xive_source_esb_read,
951     .write = xive_source_esb_write,
952     .endianness = DEVICE_BIG_ENDIAN,
953     .valid = {
954         .min_access_size = 8,
955         .max_access_size = 8,
956     },
957     .impl = {
958         .min_access_size = 8,
959         .max_access_size = 8,
960     },
961 };
962 
963 void xive_source_set_irq(void *opaque, int srcno, int val)
964 {
965     XiveSource *xsrc = XIVE_SOURCE(opaque);
966     bool notify = false;
967 
968     if (xive_source_irq_is_lsi(xsrc, srcno)) {
969         if (val) {
970             notify = xive_source_lsi_trigger(xsrc, srcno);
971         } else {
972             xsrc->status[srcno] &= ~XIVE_STATUS_ASSERTED;
973         }
974     } else {
975         if (val) {
976             notify = xive_source_esb_trigger(xsrc, srcno);
977         }
978     }
979 
980     /* Forward the source event notification for routing */
981     if (notify) {
982         xive_source_notify(xsrc, srcno);
983     }
984 }
985 
986 void xive_source_pic_print_info(XiveSource *xsrc, uint32_t offset, Monitor *mon)
987 {
988     int i;
989 
990     for (i = 0; i < xsrc->nr_irqs; i++) {
991         uint8_t pq = xive_source_esb_get(xsrc, i);
992 
993         if (pq == XIVE_ESB_OFF) {
994             continue;
995         }
996 
997         monitor_printf(mon, "  %08x %s %c%c%c\n", i + offset,
998                        xive_source_irq_is_lsi(xsrc, i) ? "LSI" : "MSI",
999                        pq & XIVE_ESB_VAL_P ? 'P' : '-',
1000                        pq & XIVE_ESB_VAL_Q ? 'Q' : '-',
1001                        xsrc->status[i] & XIVE_STATUS_ASSERTED ? 'A' : ' ');
1002     }
1003 }
1004 
1005 static void xive_source_reset(void *dev)
1006 {
1007     XiveSource *xsrc = XIVE_SOURCE(dev);
1008 
1009     /* Do not clear the LSI bitmap */
1010 
1011     /* PQs are initialized to 0b01 (Q=1) which corresponds to "ints off" */
1012     memset(xsrc->status, XIVE_ESB_OFF, xsrc->nr_irqs);
1013 }
1014 
1015 static void xive_source_realize(DeviceState *dev, Error **errp)
1016 {
1017     XiveSource *xsrc = XIVE_SOURCE(dev);
1018     Object *obj;
1019     Error *local_err = NULL;
1020 
1021     obj = object_property_get_link(OBJECT(dev), "xive", &local_err);
1022     if (!obj) {
1023         error_propagate(errp, local_err);
1024         error_prepend(errp, "required link 'xive' not found: ");
1025         return;
1026     }
1027 
1028     xsrc->xive = XIVE_NOTIFIER(obj);
1029 
1030     if (!xsrc->nr_irqs) {
1031         error_setg(errp, "Number of interrupt needs to be greater than 0");
1032         return;
1033     }
1034 
1035     if (xsrc->esb_shift != XIVE_ESB_4K &&
1036         xsrc->esb_shift != XIVE_ESB_4K_2PAGE &&
1037         xsrc->esb_shift != XIVE_ESB_64K &&
1038         xsrc->esb_shift != XIVE_ESB_64K_2PAGE) {
1039         error_setg(errp, "Invalid ESB shift setting");
1040         return;
1041     }
1042 
1043     xsrc->status = g_malloc0(xsrc->nr_irqs);
1044     xsrc->lsi_map = bitmap_new(xsrc->nr_irqs);
1045 
1046     if (!kvm_irqchip_in_kernel()) {
1047         memory_region_init_io(&xsrc->esb_mmio, OBJECT(xsrc),
1048                               &xive_source_esb_ops, xsrc, "xive.esb",
1049                               (1ull << xsrc->esb_shift) * xsrc->nr_irqs);
1050     }
1051 
1052     qemu_register_reset(xive_source_reset, dev);
1053 }
1054 
1055 static const VMStateDescription vmstate_xive_source = {
1056     .name = TYPE_XIVE_SOURCE,
1057     .version_id = 1,
1058     .minimum_version_id = 1,
1059     .fields = (VMStateField[]) {
1060         VMSTATE_UINT32_EQUAL(nr_irqs, XiveSource, NULL),
1061         VMSTATE_VBUFFER_UINT32(status, XiveSource, 1, NULL, nr_irqs),
1062         VMSTATE_END_OF_LIST()
1063     },
1064 };
1065 
1066 /*
1067  * The default XIVE interrupt source setting for the ESB MMIOs is two
1068  * 64k pages without Store EOI, to be in sync with KVM.
1069  */
1070 static Property xive_source_properties[] = {
1071     DEFINE_PROP_UINT64("flags", XiveSource, esb_flags, 0),
1072     DEFINE_PROP_UINT32("nr-irqs", XiveSource, nr_irqs, 0),
1073     DEFINE_PROP_UINT32("shift", XiveSource, esb_shift, XIVE_ESB_64K_2PAGE),
1074     DEFINE_PROP_END_OF_LIST(),
1075 };
1076 
1077 static void xive_source_class_init(ObjectClass *klass, void *data)
1078 {
1079     DeviceClass *dc = DEVICE_CLASS(klass);
1080 
1081     dc->desc    = "XIVE Interrupt Source";
1082     dc->props   = xive_source_properties;
1083     dc->realize = xive_source_realize;
1084     dc->vmsd    = &vmstate_xive_source;
1085 }
1086 
1087 static const TypeInfo xive_source_info = {
1088     .name          = TYPE_XIVE_SOURCE,
1089     .parent        = TYPE_DEVICE,
1090     .instance_size = sizeof(XiveSource),
1091     .class_init    = xive_source_class_init,
1092 };
1093 
1094 /*
1095  * XiveEND helpers
1096  */
1097 
1098 void xive_end_queue_pic_print_info(XiveEND *end, uint32_t width, Monitor *mon)
1099 {
1100     uint64_t qaddr_base = xive_end_qaddr(end);
1101     uint32_t qsize = xive_get_field32(END_W0_QSIZE, end->w0);
1102     uint32_t qindex = xive_get_field32(END_W1_PAGE_OFF, end->w1);
1103     uint32_t qentries = 1 << (qsize + 10);
1104     int i;
1105 
1106     /*
1107      * print out the [ (qindex - (width - 1)) .. (qindex + 1)] window
1108      */
1109     monitor_printf(mon, " [ ");
1110     qindex = (qindex - (width - 1)) & (qentries - 1);
1111     for (i = 0; i < width; i++) {
1112         uint64_t qaddr = qaddr_base + (qindex << 2);
1113         uint32_t qdata = -1;
1114 
1115         if (dma_memory_read(&address_space_memory, qaddr, &qdata,
1116                             sizeof(qdata))) {
1117             qemu_log_mask(LOG_GUEST_ERROR, "XIVE: failed to read EQ @0x%"
1118                           HWADDR_PRIx "\n", qaddr);
1119             return;
1120         }
1121         monitor_printf(mon, "%s%08x ", i == width - 1 ? "^" : "",
1122                        be32_to_cpu(qdata));
1123         qindex = (qindex + 1) & (qentries - 1);
1124     }
1125 }
1126 
1127 void xive_end_pic_print_info(XiveEND *end, uint32_t end_idx, Monitor *mon)
1128 {
1129     uint64_t qaddr_base = xive_end_qaddr(end);
1130     uint32_t qindex = xive_get_field32(END_W1_PAGE_OFF, end->w1);
1131     uint32_t qgen = xive_get_field32(END_W1_GENERATION, end->w1);
1132     uint32_t qsize = xive_get_field32(END_W0_QSIZE, end->w0);
1133     uint32_t qentries = 1 << (qsize + 10);
1134 
1135     uint32_t nvt = xive_get_field32(END_W6_NVT_INDEX, end->w6);
1136     uint8_t priority = xive_get_field32(END_W7_F0_PRIORITY, end->w7);
1137 
1138     if (!xive_end_is_valid(end)) {
1139         return;
1140     }
1141 
1142     monitor_printf(mon, "  %08x %c%c%c%c%c prio:%d nvt:%04x eq:@%08"PRIx64
1143                    "% 6d/%5d ^%d", end_idx,
1144                    xive_end_is_valid(end)    ? 'v' : '-',
1145                    xive_end_is_enqueue(end)  ? 'q' : '-',
1146                    xive_end_is_notify(end)   ? 'n' : '-',
1147                    xive_end_is_backlog(end)  ? 'b' : '-',
1148                    xive_end_is_escalate(end) ? 'e' : '-',
1149                    priority, nvt, qaddr_base, qindex, qentries, qgen);
1150 
1151     xive_end_queue_pic_print_info(end, 6, mon);
1152     monitor_printf(mon, "]\n");
1153 }
1154 
1155 static void xive_end_enqueue(XiveEND *end, uint32_t data)
1156 {
1157     uint64_t qaddr_base = xive_end_qaddr(end);
1158     uint32_t qsize = xive_get_field32(END_W0_QSIZE, end->w0);
1159     uint32_t qindex = xive_get_field32(END_W1_PAGE_OFF, end->w1);
1160     uint32_t qgen = xive_get_field32(END_W1_GENERATION, end->w1);
1161 
1162     uint64_t qaddr = qaddr_base + (qindex << 2);
1163     uint32_t qdata = cpu_to_be32((qgen << 31) | (data & 0x7fffffff));
1164     uint32_t qentries = 1 << (qsize + 10);
1165 
1166     if (dma_memory_write(&address_space_memory, qaddr, &qdata, sizeof(qdata))) {
1167         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: failed to write END data @0x%"
1168                       HWADDR_PRIx "\n", qaddr);
1169         return;
1170     }
1171 
1172     qindex = (qindex + 1) & (qentries - 1);
1173     if (qindex == 0) {
1174         qgen ^= 1;
1175         end->w1 = xive_set_field32(END_W1_GENERATION, end->w1, qgen);
1176     }
1177     end->w1 = xive_set_field32(END_W1_PAGE_OFF, end->w1, qindex);
1178 }
1179 
1180 /*
1181  * XIVE Router (aka. Virtualization Controller or IVRE)
1182  */
1183 
1184 int xive_router_get_eas(XiveRouter *xrtr, uint8_t eas_blk, uint32_t eas_idx,
1185                         XiveEAS *eas)
1186 {
1187     XiveRouterClass *xrc = XIVE_ROUTER_GET_CLASS(xrtr);
1188 
1189     return xrc->get_eas(xrtr, eas_blk, eas_idx, eas);
1190 }
1191 
1192 int xive_router_get_end(XiveRouter *xrtr, uint8_t end_blk, uint32_t end_idx,
1193                         XiveEND *end)
1194 {
1195    XiveRouterClass *xrc = XIVE_ROUTER_GET_CLASS(xrtr);
1196 
1197    return xrc->get_end(xrtr, end_blk, end_idx, end);
1198 }
1199 
1200 int xive_router_write_end(XiveRouter *xrtr, uint8_t end_blk, uint32_t end_idx,
1201                           XiveEND *end, uint8_t word_number)
1202 {
1203    XiveRouterClass *xrc = XIVE_ROUTER_GET_CLASS(xrtr);
1204 
1205    return xrc->write_end(xrtr, end_blk, end_idx, end, word_number);
1206 }
1207 
1208 int xive_router_get_nvt(XiveRouter *xrtr, uint8_t nvt_blk, uint32_t nvt_idx,
1209                         XiveNVT *nvt)
1210 {
1211    XiveRouterClass *xrc = XIVE_ROUTER_GET_CLASS(xrtr);
1212 
1213    return xrc->get_nvt(xrtr, nvt_blk, nvt_idx, nvt);
1214 }
1215 
1216 int xive_router_write_nvt(XiveRouter *xrtr, uint8_t nvt_blk, uint32_t nvt_idx,
1217                         XiveNVT *nvt, uint8_t word_number)
1218 {
1219    XiveRouterClass *xrc = XIVE_ROUTER_GET_CLASS(xrtr);
1220 
1221    return xrc->write_nvt(xrtr, nvt_blk, nvt_idx, nvt, word_number);
1222 }
1223 
1224 XiveTCTX *xive_router_get_tctx(XiveRouter *xrtr, CPUState *cs)
1225 {
1226     XiveRouterClass *xrc = XIVE_ROUTER_GET_CLASS(xrtr);
1227 
1228     return xrc->get_tctx(xrtr, cs);
1229 }
1230 
1231 /*
1232  * By default on P9, the HW CAM line (23bits) is hardwired to :
1233  *
1234  *   0x000||0b1||4Bit chip number||7Bit Thread number.
1235  *
1236  * When the block grouping is enabled, the CAM line is changed to :
1237  *
1238  *   4Bit chip number||0x001||7Bit Thread number.
1239  */
1240 static uint32_t hw_cam_line(uint8_t chip_id, uint8_t tid)
1241 {
1242     return 1 << 11 | (chip_id & 0xf) << 7 | (tid & 0x7f);
1243 }
1244 
1245 static bool xive_presenter_tctx_match_hw(XiveTCTX *tctx,
1246                                          uint8_t nvt_blk, uint32_t nvt_idx)
1247 {
1248     CPUPPCState *env = &POWERPC_CPU(tctx->cs)->env;
1249     uint32_t pir = env->spr_cb[SPR_PIR].default_value;
1250 
1251     return hw_cam_line((pir >> 8) & 0xf, pir & 0x7f) ==
1252         hw_cam_line(nvt_blk, nvt_idx);
1253 }
1254 
1255 /*
1256  * The thread context register words are in big-endian format.
1257  */
1258 static int xive_presenter_tctx_match(XiveTCTX *tctx, uint8_t format,
1259                                      uint8_t nvt_blk, uint32_t nvt_idx,
1260                                      bool cam_ignore, uint32_t logic_serv)
1261 {
1262     uint32_t cam = xive_nvt_cam_line(nvt_blk, nvt_idx);
1263     uint32_t qw3w2 = xive_tctx_word2(&tctx->regs[TM_QW3_HV_PHYS]);
1264     uint32_t qw2w2 = xive_tctx_word2(&tctx->regs[TM_QW2_HV_POOL]);
1265     uint32_t qw1w2 = xive_tctx_word2(&tctx->regs[TM_QW1_OS]);
1266     uint32_t qw0w2 = xive_tctx_word2(&tctx->regs[TM_QW0_USER]);
1267 
1268     /*
1269      * TODO (PowerNV): ignore mode. The low order bits of the NVT
1270      * identifier are ignored in the "CAM" match.
1271      */
1272 
1273     if (format == 0) {
1274         if (cam_ignore == true) {
1275             /*
1276              * F=0 & i=1: Logical server notification (bits ignored at
1277              * the end of the NVT identifier)
1278              */
1279             qemu_log_mask(LOG_UNIMP, "XIVE: no support for LS NVT %x/%x\n",
1280                           nvt_blk, nvt_idx);
1281              return -1;
1282         }
1283 
1284         /* F=0 & i=0: Specific NVT notification */
1285 
1286         /* PHYS ring */
1287         if ((be32_to_cpu(qw3w2) & TM_QW3W2_VT) &&
1288             xive_presenter_tctx_match_hw(tctx, nvt_blk, nvt_idx)) {
1289             return TM_QW3_HV_PHYS;
1290         }
1291 
1292         /* HV POOL ring */
1293         if ((be32_to_cpu(qw2w2) & TM_QW2W2_VP) &&
1294             cam == xive_get_field32(TM_QW2W2_POOL_CAM, qw2w2)) {
1295             return TM_QW2_HV_POOL;
1296         }
1297 
1298         /* OS ring */
1299         if ((be32_to_cpu(qw1w2) & TM_QW1W2_VO) &&
1300             cam == xive_get_field32(TM_QW1W2_OS_CAM, qw1w2)) {
1301             return TM_QW1_OS;
1302         }
1303     } else {
1304         /* F=1 : User level Event-Based Branch (EBB) notification */
1305 
1306         /* USER ring */
1307         if  ((be32_to_cpu(qw1w2) & TM_QW1W2_VO) &&
1308              (cam == xive_get_field32(TM_QW1W2_OS_CAM, qw1w2)) &&
1309              (be32_to_cpu(qw0w2) & TM_QW0W2_VU) &&
1310              (logic_serv == xive_get_field32(TM_QW0W2_LOGIC_SERV, qw0w2))) {
1311             return TM_QW0_USER;
1312         }
1313     }
1314     return -1;
1315 }
1316 
1317 typedef struct XiveTCTXMatch {
1318     XiveTCTX *tctx;
1319     uint8_t ring;
1320 } XiveTCTXMatch;
1321 
1322 static bool xive_presenter_match(XiveRouter *xrtr, uint8_t format,
1323                                  uint8_t nvt_blk, uint32_t nvt_idx,
1324                                  bool cam_ignore, uint8_t priority,
1325                                  uint32_t logic_serv, XiveTCTXMatch *match)
1326 {
1327     CPUState *cs;
1328 
1329     /*
1330      * TODO (PowerNV): handle chip_id overwrite of block field for
1331      * hardwired CAM compares
1332      */
1333 
1334     CPU_FOREACH(cs) {
1335         XiveTCTX *tctx = xive_router_get_tctx(xrtr, cs);
1336         int ring;
1337 
1338         /*
1339          * HW checks that the CPU is enabled in the Physical Thread
1340          * Enable Register (PTER).
1341          */
1342 
1343         /*
1344          * Check the thread context CAM lines and record matches. We
1345          * will handle CPU exception delivery later
1346          */
1347         ring = xive_presenter_tctx_match(tctx, format, nvt_blk, nvt_idx,
1348                                          cam_ignore, logic_serv);
1349         /*
1350          * Save the context and follow on to catch duplicates, that we
1351          * don't support yet.
1352          */
1353         if (ring != -1) {
1354             if (match->tctx) {
1355                 qemu_log_mask(LOG_GUEST_ERROR, "XIVE: already found a thread "
1356                               "context NVT %x/%x\n", nvt_blk, nvt_idx);
1357                 return false;
1358             }
1359 
1360             match->ring = ring;
1361             match->tctx = tctx;
1362         }
1363     }
1364 
1365     if (!match->tctx) {
1366         qemu_log_mask(LOG_UNIMP, "XIVE: NVT %x/%x is not dispatched\n",
1367                       nvt_blk, nvt_idx);
1368         return false;
1369     }
1370 
1371     return true;
1372 }
1373 
1374 /*
1375  * This is our simple Xive Presenter Engine model. It is merged in the
1376  * Router as it does not require an extra object.
1377  *
1378  * It receives notification requests sent by the IVRE to find one
1379  * matching NVT (or more) dispatched on the processor threads. In case
1380  * of a single NVT notification, the process is abreviated and the
1381  * thread is signaled if a match is found. In case of a logical server
1382  * notification (bits ignored at the end of the NVT identifier), the
1383  * IVPE and IVRE select a winning thread using different filters. This
1384  * involves 2 or 3 exchanges on the PowerBus that the model does not
1385  * support.
1386  *
1387  * The parameters represent what is sent on the PowerBus
1388  */
1389 static void xive_presenter_notify(XiveRouter *xrtr, uint8_t format,
1390                                   uint8_t nvt_blk, uint32_t nvt_idx,
1391                                   bool cam_ignore, uint8_t priority,
1392                                   uint32_t logic_serv)
1393 {
1394     XiveNVT nvt;
1395     XiveTCTXMatch match = { .tctx = NULL, .ring = 0 };
1396     bool found;
1397 
1398     /* NVT cache lookup */
1399     if (xive_router_get_nvt(xrtr, nvt_blk, nvt_idx, &nvt)) {
1400         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: no NVT %x/%x\n",
1401                       nvt_blk, nvt_idx);
1402         return;
1403     }
1404 
1405     if (!xive_nvt_is_valid(&nvt)) {
1406         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: NVT %x/%x is invalid\n",
1407                       nvt_blk, nvt_idx);
1408         return;
1409     }
1410 
1411     found = xive_presenter_match(xrtr, format, nvt_blk, nvt_idx, cam_ignore,
1412                                  priority, logic_serv, &match);
1413     if (found) {
1414         ipb_update(&match.tctx->regs[match.ring], priority);
1415         xive_tctx_notify(match.tctx, match.ring);
1416         return;
1417     }
1418 
1419     /* Record the IPB in the associated NVT structure */
1420     ipb_update((uint8_t *) &nvt.w4, priority);
1421     xive_router_write_nvt(xrtr, nvt_blk, nvt_idx, &nvt, 4);
1422 
1423     /*
1424      * If no matching NVT is dispatched on a HW thread :
1425      * - update the NVT structure if backlog is activated
1426      * - escalate (ESe PQ bits and EAS in w4-5) if escalation is
1427      *   activated
1428      */
1429 }
1430 
1431 /*
1432  * An END trigger can come from an event trigger (IPI or HW) or from
1433  * another chip. We don't model the PowerBus but the END trigger
1434  * message has the same parameters than in the function below.
1435  */
1436 static void xive_router_end_notify(XiveRouter *xrtr, uint8_t end_blk,
1437                                    uint32_t end_idx, uint32_t end_data)
1438 {
1439     XiveEND end;
1440     uint8_t priority;
1441     uint8_t format;
1442 
1443     /* END cache lookup */
1444     if (xive_router_get_end(xrtr, end_blk, end_idx, &end)) {
1445         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: No END %x/%x\n", end_blk,
1446                       end_idx);
1447         return;
1448     }
1449 
1450     if (!xive_end_is_valid(&end)) {
1451         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: END %x/%x is invalid\n",
1452                       end_blk, end_idx);
1453         return;
1454     }
1455 
1456     if (xive_end_is_enqueue(&end)) {
1457         xive_end_enqueue(&end, end_data);
1458         /* Enqueuing event data modifies the EQ toggle and index */
1459         xive_router_write_end(xrtr, end_blk, end_idx, &end, 1);
1460     }
1461 
1462     /*
1463      * The W7 format depends on the F bit in W6. It defines the type
1464      * of the notification :
1465      *
1466      *   F=0 : single or multiple NVT notification
1467      *   F=1 : User level Event-Based Branch (EBB) notification, no
1468      *         priority
1469      */
1470     format = xive_get_field32(END_W6_FORMAT_BIT, end.w6);
1471     priority = xive_get_field32(END_W7_F0_PRIORITY, end.w7);
1472 
1473     /* The END is masked */
1474     if (format == 0 && priority == 0xff) {
1475         return;
1476     }
1477 
1478     /*
1479      * Check the END ESn (Event State Buffer for notification) for
1480      * even futher coalescing in the Router
1481      */
1482     if (!xive_end_is_notify(&end)) {
1483         uint8_t pq = xive_get_field32(END_W1_ESn, end.w1);
1484         bool notify = xive_esb_trigger(&pq);
1485 
1486         if (pq != xive_get_field32(END_W1_ESn, end.w1)) {
1487             end.w1 = xive_set_field32(END_W1_ESn, end.w1, pq);
1488             xive_router_write_end(xrtr, end_blk, end_idx, &end, 1);
1489         }
1490 
1491         /* ESn[Q]=1 : end of notification */
1492         if (!notify) {
1493             return;
1494         }
1495     }
1496 
1497     /*
1498      * Follows IVPE notification
1499      */
1500     xive_presenter_notify(xrtr, format,
1501                           xive_get_field32(END_W6_NVT_BLOCK, end.w6),
1502                           xive_get_field32(END_W6_NVT_INDEX, end.w6),
1503                           xive_get_field32(END_W7_F0_IGNORE, end.w7),
1504                           priority,
1505                           xive_get_field32(END_W7_F1_LOG_SERVER_ID, end.w7));
1506 
1507     /* TODO: Auto EOI. */
1508 }
1509 
1510 void xive_router_notify(XiveNotifier *xn, uint32_t lisn)
1511 {
1512     XiveRouter *xrtr = XIVE_ROUTER(xn);
1513     uint8_t eas_blk = XIVE_SRCNO_BLOCK(lisn);
1514     uint32_t eas_idx = XIVE_SRCNO_INDEX(lisn);
1515     XiveEAS eas;
1516 
1517     /* EAS cache lookup */
1518     if (xive_router_get_eas(xrtr, eas_blk, eas_idx, &eas)) {
1519         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: Unknown LISN %x\n", lisn);
1520         return;
1521     }
1522 
1523     /*
1524      * The IVRE checks the State Bit Cache at this point. We skip the
1525      * SBC lookup because the state bits of the sources are modeled
1526      * internally in QEMU.
1527      */
1528 
1529     if (!xive_eas_is_valid(&eas)) {
1530         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: invalid LISN %x\n", lisn);
1531         return;
1532     }
1533 
1534     if (xive_eas_is_masked(&eas)) {
1535         /* Notification completed */
1536         return;
1537     }
1538 
1539     /*
1540      * The event trigger becomes an END trigger
1541      */
1542     xive_router_end_notify(xrtr,
1543                            xive_get_field64(EAS_END_BLOCK, eas.w),
1544                            xive_get_field64(EAS_END_INDEX, eas.w),
1545                            xive_get_field64(EAS_END_DATA,  eas.w));
1546 }
1547 
1548 static void xive_router_class_init(ObjectClass *klass, void *data)
1549 {
1550     DeviceClass *dc = DEVICE_CLASS(klass);
1551     XiveNotifierClass *xnc = XIVE_NOTIFIER_CLASS(klass);
1552 
1553     dc->desc    = "XIVE Router Engine";
1554     xnc->notify = xive_router_notify;
1555 }
1556 
1557 static const TypeInfo xive_router_info = {
1558     .name          = TYPE_XIVE_ROUTER,
1559     .parent        = TYPE_SYS_BUS_DEVICE,
1560     .abstract      = true,
1561     .class_size    = sizeof(XiveRouterClass),
1562     .class_init    = xive_router_class_init,
1563     .interfaces    = (InterfaceInfo[]) {
1564         { TYPE_XIVE_NOTIFIER },
1565         { }
1566     }
1567 };
1568 
1569 void xive_eas_pic_print_info(XiveEAS *eas, uint32_t lisn, Monitor *mon)
1570 {
1571     if (!xive_eas_is_valid(eas)) {
1572         return;
1573     }
1574 
1575     monitor_printf(mon, "  %08x %s end:%02x/%04x data:%08x\n",
1576                    lisn, xive_eas_is_masked(eas) ? "M" : " ",
1577                    (uint8_t)  xive_get_field64(EAS_END_BLOCK, eas->w),
1578                    (uint32_t) xive_get_field64(EAS_END_INDEX, eas->w),
1579                    (uint32_t) xive_get_field64(EAS_END_DATA, eas->w));
1580 }
1581 
1582 /*
1583  * END ESB MMIO loads
1584  */
1585 static uint64_t xive_end_source_read(void *opaque, hwaddr addr, unsigned size)
1586 {
1587     XiveENDSource *xsrc = XIVE_END_SOURCE(opaque);
1588     uint32_t offset = addr & 0xFFF;
1589     uint8_t end_blk;
1590     uint32_t end_idx;
1591     XiveEND end;
1592     uint32_t end_esmask;
1593     uint8_t pq;
1594     uint64_t ret = -1;
1595 
1596     end_blk = xsrc->block_id;
1597     end_idx = addr >> (xsrc->esb_shift + 1);
1598 
1599     if (xive_router_get_end(xsrc->xrtr, end_blk, end_idx, &end)) {
1600         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: No END %x/%x\n", end_blk,
1601                       end_idx);
1602         return -1;
1603     }
1604 
1605     if (!xive_end_is_valid(&end)) {
1606         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: END %x/%x is invalid\n",
1607                       end_blk, end_idx);
1608         return -1;
1609     }
1610 
1611     end_esmask = addr_is_even(addr, xsrc->esb_shift) ? END_W1_ESn : END_W1_ESe;
1612     pq = xive_get_field32(end_esmask, end.w1);
1613 
1614     switch (offset) {
1615     case XIVE_ESB_LOAD_EOI ... XIVE_ESB_LOAD_EOI + 0x7FF:
1616         ret = xive_esb_eoi(&pq);
1617 
1618         /* Forward the source event notification for routing ?? */
1619         break;
1620 
1621     case XIVE_ESB_GET ... XIVE_ESB_GET + 0x3FF:
1622         ret = pq;
1623         break;
1624 
1625     case XIVE_ESB_SET_PQ_00 ... XIVE_ESB_SET_PQ_00 + 0x0FF:
1626     case XIVE_ESB_SET_PQ_01 ... XIVE_ESB_SET_PQ_01 + 0x0FF:
1627     case XIVE_ESB_SET_PQ_10 ... XIVE_ESB_SET_PQ_10 + 0x0FF:
1628     case XIVE_ESB_SET_PQ_11 ... XIVE_ESB_SET_PQ_11 + 0x0FF:
1629         ret = xive_esb_set(&pq, (offset >> 8) & 0x3);
1630         break;
1631     default:
1632         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: invalid END ESB load addr %d\n",
1633                       offset);
1634         return -1;
1635     }
1636 
1637     if (pq != xive_get_field32(end_esmask, end.w1)) {
1638         end.w1 = xive_set_field32(end_esmask, end.w1, pq);
1639         xive_router_write_end(xsrc->xrtr, end_blk, end_idx, &end, 1);
1640     }
1641 
1642     return ret;
1643 }
1644 
1645 /*
1646  * END ESB MMIO stores are invalid
1647  */
1648 static void xive_end_source_write(void *opaque, hwaddr addr,
1649                                   uint64_t value, unsigned size)
1650 {
1651     qemu_log_mask(LOG_GUEST_ERROR, "XIVE: invalid ESB write addr 0x%"
1652                   HWADDR_PRIx"\n", addr);
1653 }
1654 
1655 static const MemoryRegionOps xive_end_source_ops = {
1656     .read = xive_end_source_read,
1657     .write = xive_end_source_write,
1658     .endianness = DEVICE_BIG_ENDIAN,
1659     .valid = {
1660         .min_access_size = 8,
1661         .max_access_size = 8,
1662     },
1663     .impl = {
1664         .min_access_size = 8,
1665         .max_access_size = 8,
1666     },
1667 };
1668 
1669 static void xive_end_source_realize(DeviceState *dev, Error **errp)
1670 {
1671     XiveENDSource *xsrc = XIVE_END_SOURCE(dev);
1672     Object *obj;
1673     Error *local_err = NULL;
1674 
1675     obj = object_property_get_link(OBJECT(dev), "xive", &local_err);
1676     if (!obj) {
1677         error_propagate(errp, local_err);
1678         error_prepend(errp, "required link 'xive' not found: ");
1679         return;
1680     }
1681 
1682     xsrc->xrtr = XIVE_ROUTER(obj);
1683 
1684     if (!xsrc->nr_ends) {
1685         error_setg(errp, "Number of interrupt needs to be greater than 0");
1686         return;
1687     }
1688 
1689     if (xsrc->esb_shift != XIVE_ESB_4K &&
1690         xsrc->esb_shift != XIVE_ESB_64K) {
1691         error_setg(errp, "Invalid ESB shift setting");
1692         return;
1693     }
1694 
1695     /*
1696      * Each END is assigned an even/odd pair of MMIO pages, the even page
1697      * manages the ESn field while the odd page manages the ESe field.
1698      */
1699     memory_region_init_io(&xsrc->esb_mmio, OBJECT(xsrc),
1700                           &xive_end_source_ops, xsrc, "xive.end",
1701                           (1ull << (xsrc->esb_shift + 1)) * xsrc->nr_ends);
1702 }
1703 
1704 static Property xive_end_source_properties[] = {
1705     DEFINE_PROP_UINT8("block-id", XiveENDSource, block_id, 0),
1706     DEFINE_PROP_UINT32("nr-ends", XiveENDSource, nr_ends, 0),
1707     DEFINE_PROP_UINT32("shift", XiveENDSource, esb_shift, XIVE_ESB_64K),
1708     DEFINE_PROP_END_OF_LIST(),
1709 };
1710 
1711 static void xive_end_source_class_init(ObjectClass *klass, void *data)
1712 {
1713     DeviceClass *dc = DEVICE_CLASS(klass);
1714 
1715     dc->desc    = "XIVE END Source";
1716     dc->props   = xive_end_source_properties;
1717     dc->realize = xive_end_source_realize;
1718 }
1719 
1720 static const TypeInfo xive_end_source_info = {
1721     .name          = TYPE_XIVE_END_SOURCE,
1722     .parent        = TYPE_DEVICE,
1723     .instance_size = sizeof(XiveENDSource),
1724     .class_init    = xive_end_source_class_init,
1725 };
1726 
1727 /*
1728  * XIVE Notifier
1729  */
1730 static const TypeInfo xive_notifier_info = {
1731     .name = TYPE_XIVE_NOTIFIER,
1732     .parent = TYPE_INTERFACE,
1733     .class_size = sizeof(XiveNotifierClass),
1734 };
1735 
1736 static void xive_register_types(void)
1737 {
1738     type_register_static(&xive_source_info);
1739     type_register_static(&xive_notifier_info);
1740     type_register_static(&xive_router_info);
1741     type_register_static(&xive_end_source_info);
1742     type_register_static(&xive_tctx_info);
1743 }
1744 
1745 type_init(xive_register_types)
1746