xref: /openbmc/qemu/hw/riscv/riscv-iommu.c (revision e93d2c5fdd151241ace5090bb4a2d381626ee4bf)
1 /*
2  * QEMU emulation of an RISC-V IOMMU
3  *
4  * Copyright (C) 2021-2023, Rivos Inc.
5  *
6  * This program is free software; you can redistribute it and/or modify it
7  * under the terms and conditions of the GNU General Public License,
8  * version 2 or later, as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License along
16  * with this program; if not, see <http://www.gnu.org/licenses/>.
17  */
18 
19 #include "qemu/osdep.h"
20 #include "qom/object.h"
21 #include "exec/target_page.h"
22 #include "hw/pci/pci_bus.h"
23 #include "hw/pci/pci_device.h"
24 #include "hw/qdev-properties.h"
25 #include "hw/riscv/riscv_hart.h"
26 #include "migration/vmstate.h"
27 #include "qapi/error.h"
28 #include "qemu/timer.h"
29 
30 #include "cpu_bits.h"
31 #include "riscv-iommu.h"
32 #include "riscv-iommu-bits.h"
33 #include "riscv-iommu-hpm.h"
34 #include "trace.h"
35 
36 #define LIMIT_CACHE_CTX               (1U << 7)
37 #define LIMIT_CACHE_IOT               (1U << 20)
38 
39 /* Physical page number coversions */
40 #define PPN_PHYS(ppn)                 ((ppn) << TARGET_PAGE_BITS)
41 #define PPN_DOWN(phy)                 ((phy) >> TARGET_PAGE_BITS)
42 
43 typedef struct RISCVIOMMUEntry RISCVIOMMUEntry;
44 
45 /* Device assigned I/O address space */
46 struct RISCVIOMMUSpace {
47     IOMMUMemoryRegion iova_mr;  /* IOVA memory region for attached device */
48     AddressSpace iova_as;       /* IOVA address space for attached device */
49     RISCVIOMMUState *iommu;     /* Managing IOMMU device state */
50     uint32_t devid;             /* Requester identifier, AKA device_id */
51     bool notifier;              /* IOMMU unmap notifier enabled */
52     QLIST_ENTRY(RISCVIOMMUSpace) list;
53 };
54 
55 typedef enum RISCVIOMMUTransTag {
56     RISCV_IOMMU_TRANS_TAG_BY,  /* Bypass */
57     RISCV_IOMMU_TRANS_TAG_SS,  /* Single Stage */
58     RISCV_IOMMU_TRANS_TAG_VG,  /* G-stage only */
59     RISCV_IOMMU_TRANS_TAG_VN,  /* Nested translation */
60 } RISCVIOMMUTransTag;
61 
62 /* Address translation cache entry */
63 struct RISCVIOMMUEntry {
64     RISCVIOMMUTransTag tag;     /* Translation Tag */
65     uint64_t iova:44;           /* IOVA Page Number */
66     uint64_t pscid:20;          /* Process Soft-Context identifier */
67     uint64_t phys:44;           /* Physical Page Number */
68     uint64_t gscid:16;          /* Guest Soft-Context identifier */
69     uint64_t perm:2;            /* IOMMU_RW flags */
70 };
71 
72 /* IOMMU index for transactions without process_id specified. */
73 #define RISCV_IOMMU_NOPROCID 0
74 
75 static uint8_t riscv_iommu_get_icvec_vector(uint32_t icvec, uint32_t vec_type)
76 {
77     switch (vec_type) {
78     case RISCV_IOMMU_INTR_CQ:
79         return icvec & RISCV_IOMMU_ICVEC_CIV;
80     case RISCV_IOMMU_INTR_FQ:
81         return (icvec & RISCV_IOMMU_ICVEC_FIV) >> 4;
82     case RISCV_IOMMU_INTR_PM:
83         return (icvec & RISCV_IOMMU_ICVEC_PMIV) >> 8;
84     case RISCV_IOMMU_INTR_PQ:
85         return (icvec & RISCV_IOMMU_ICVEC_PIV) >> 12;
86     default:
87         g_assert_not_reached();
88     }
89 }
90 
91 void riscv_iommu_notify(RISCVIOMMUState *s, int vec_type)
92 {
93     uint32_t ipsr, icvec, vector;
94 
95     if (!s->notify) {
96         return;
97     }
98 
99     icvec = riscv_iommu_reg_get32(s, RISCV_IOMMU_REG_ICVEC);
100     ipsr = riscv_iommu_reg_mod32(s, RISCV_IOMMU_REG_IPSR, (1 << vec_type), 0);
101 
102     if (!(ipsr & (1 << vec_type))) {
103         vector = riscv_iommu_get_icvec_vector(icvec, vec_type);
104         s->notify(s, vector);
105         trace_riscv_iommu_notify_int_vector(vec_type, vector);
106     }
107 }
108 
109 static void riscv_iommu_fault(RISCVIOMMUState *s,
110                               struct riscv_iommu_fq_record *ev)
111 {
112     uint32_t ctrl = riscv_iommu_reg_get32(s, RISCV_IOMMU_REG_FQCSR);
113     uint32_t head = riscv_iommu_reg_get32(s, RISCV_IOMMU_REG_FQH) & s->fq_mask;
114     uint32_t tail = riscv_iommu_reg_get32(s, RISCV_IOMMU_REG_FQT) & s->fq_mask;
115     uint32_t next = (tail + 1) & s->fq_mask;
116     uint32_t devid = get_field(ev->hdr, RISCV_IOMMU_FQ_HDR_DID);
117 
118     trace_riscv_iommu_flt(s->parent_obj.id, PCI_BUS_NUM(devid), PCI_SLOT(devid),
119                           PCI_FUNC(devid), ev->hdr, ev->iotval);
120 
121     if (!(ctrl & RISCV_IOMMU_FQCSR_FQON) ||
122         !!(ctrl & (RISCV_IOMMU_FQCSR_FQOF | RISCV_IOMMU_FQCSR_FQMF))) {
123         return;
124     }
125 
126     if (head == next) {
127         riscv_iommu_reg_mod32(s, RISCV_IOMMU_REG_FQCSR,
128                               RISCV_IOMMU_FQCSR_FQOF, 0);
129     } else {
130         dma_addr_t addr = s->fq_addr + tail * sizeof(*ev);
131         if (dma_memory_write(s->target_as, addr, ev, sizeof(*ev),
132                              MEMTXATTRS_UNSPECIFIED) != MEMTX_OK) {
133             riscv_iommu_reg_mod32(s, RISCV_IOMMU_REG_FQCSR,
134                                   RISCV_IOMMU_FQCSR_FQMF, 0);
135         } else {
136             riscv_iommu_reg_set32(s, RISCV_IOMMU_REG_FQT, next);
137         }
138     }
139 
140     if (ctrl & RISCV_IOMMU_FQCSR_FIE) {
141         riscv_iommu_notify(s, RISCV_IOMMU_INTR_FQ);
142     }
143 }
144 
145 static void riscv_iommu_pri(RISCVIOMMUState *s,
146     struct riscv_iommu_pq_record *pr)
147 {
148     uint32_t ctrl = riscv_iommu_reg_get32(s, RISCV_IOMMU_REG_PQCSR);
149     uint32_t head = riscv_iommu_reg_get32(s, RISCV_IOMMU_REG_PQH) & s->pq_mask;
150     uint32_t tail = riscv_iommu_reg_get32(s, RISCV_IOMMU_REG_PQT) & s->pq_mask;
151     uint32_t next = (tail + 1) & s->pq_mask;
152     uint32_t devid = get_field(pr->hdr, RISCV_IOMMU_PREQ_HDR_DID);
153 
154     trace_riscv_iommu_pri(s->parent_obj.id, PCI_BUS_NUM(devid), PCI_SLOT(devid),
155                           PCI_FUNC(devid), pr->payload);
156 
157     if (!(ctrl & RISCV_IOMMU_PQCSR_PQON) ||
158         !!(ctrl & (RISCV_IOMMU_PQCSR_PQOF | RISCV_IOMMU_PQCSR_PQMF))) {
159         return;
160     }
161 
162     if (head == next) {
163         riscv_iommu_reg_mod32(s, RISCV_IOMMU_REG_PQCSR,
164                               RISCV_IOMMU_PQCSR_PQOF, 0);
165     } else {
166         dma_addr_t addr = s->pq_addr + tail * sizeof(*pr);
167         if (dma_memory_write(s->target_as, addr, pr, sizeof(*pr),
168                              MEMTXATTRS_UNSPECIFIED) != MEMTX_OK) {
169             riscv_iommu_reg_mod32(s, RISCV_IOMMU_REG_PQCSR,
170                                   RISCV_IOMMU_PQCSR_PQMF, 0);
171         } else {
172             riscv_iommu_reg_set32(s, RISCV_IOMMU_REG_PQT, next);
173         }
174     }
175 
176     if (ctrl & RISCV_IOMMU_PQCSR_PIE) {
177         riscv_iommu_notify(s, RISCV_IOMMU_INTR_PQ);
178     }
179 }
180 
181 /*
182  * Discards all bits from 'val' whose matching bits in the same
183  * positions in the mask 'ext' are zeros, and packs the remaining
184  * bits from 'val' contiguously at the least-significant end of the
185  * result, keeping the same bit order as 'val' and filling any
186  * other bits at the most-significant end of the result with zeros.
187  *
188  * For example, for the following 'val' and 'ext', the return 'ret'
189  * will be:
190  *
191  * val = a b c d e f g h
192  * ext = 1 0 1 0 0 1 1 0
193  * ret = 0 0 0 0 a c f g
194  *
195  * This function, taken from the riscv-iommu 1.0 spec, section 2.3.3
196  * "Process to translate addresses of MSIs", is similar to bit manip
197  * function PEXT (Parallel bits extract) from x86.
198  */
199 static uint64_t riscv_iommu_pext_u64(uint64_t val, uint64_t ext)
200 {
201     uint64_t ret = 0;
202     uint64_t rot = 1;
203 
204     while (ext) {
205         if (ext & 1) {
206             if (val & 1) {
207                 ret |= rot;
208             }
209             rot <<= 1;
210         }
211         val >>= 1;
212         ext >>= 1;
213     }
214 
215     return ret;
216 }
217 
218 /* Check if GPA matches MSI/MRIF pattern. */
219 static bool riscv_iommu_msi_check(RISCVIOMMUState *s, RISCVIOMMUContext *ctx,
220     dma_addr_t gpa)
221 {
222     if (!s->enable_msi) {
223         return false;
224     }
225 
226     if (get_field(ctx->msiptp, RISCV_IOMMU_DC_MSIPTP_MODE) !=
227         RISCV_IOMMU_DC_MSIPTP_MODE_FLAT) {
228         return false; /* Invalid MSI/MRIF mode */
229     }
230 
231     if ((PPN_DOWN(gpa) ^ ctx->msi_addr_pattern) & ~ctx->msi_addr_mask) {
232         return false; /* GPA not in MSI range defined by AIA IMSIC rules. */
233     }
234 
235     return true;
236 }
237 
238 /*
239  * RISCV IOMMU Address Translation Lookup - Page Table Walk
240  *
241  * Note: Code is based on get_physical_address() from target/riscv/cpu_helper.c
242  * Both implementation can be merged into single helper function in future.
243  * Keeping them separate for now, as error reporting and flow specifics are
244  * sufficiently different for separate implementation.
245  *
246  * @s        : IOMMU Device State
247  * @ctx      : Translation context for device id and process address space id.
248  * @iotlb    : translation data: physical address and access mode.
249  * @return   : success or fault cause code.
250  */
251 static int riscv_iommu_spa_fetch(RISCVIOMMUState *s, RISCVIOMMUContext *ctx,
252     IOMMUTLBEntry *iotlb)
253 {
254     dma_addr_t addr, base;
255     uint64_t satp, gatp, pte;
256     bool en_s, en_g;
257     struct {
258         unsigned char step;
259         unsigned char levels;
260         unsigned char ptidxbits;
261         unsigned char ptesize;
262     } sc[2];
263     /* Translation stage phase */
264     enum {
265         S_STAGE = 0,
266         G_STAGE = 1,
267     } pass;
268     MemTxResult ret;
269 
270     satp = get_field(ctx->satp, RISCV_IOMMU_ATP_MODE_FIELD);
271     gatp = get_field(ctx->gatp, RISCV_IOMMU_ATP_MODE_FIELD);
272 
273     en_s = satp != RISCV_IOMMU_DC_FSC_MODE_BARE;
274     en_g = gatp != RISCV_IOMMU_DC_IOHGATP_MODE_BARE;
275 
276     /*
277      * Early check for MSI address match when IOVA == GPA.
278      * Note that the (!en_s) condition means that the MSI
279      * page table may only be used when guest pages are
280      * mapped using the g-stage page table, whether single-
281      * or two-stage paging is enabled. It's unavoidable though,
282      * because the spec mandates that we do a first-stage
283      * translation before we check the MSI page table, which
284      * means we can't do an early MSI check unless we have
285      * strictly !en_s.
286      */
287     if (!en_s && (iotlb->perm & IOMMU_WO) &&
288         riscv_iommu_msi_check(s, ctx, iotlb->iova)) {
289         iotlb->target_as = &s->trap_as;
290         iotlb->translated_addr = iotlb->iova;
291         iotlb->addr_mask = ~TARGET_PAGE_MASK;
292         return 0;
293     }
294 
295     /* Exit early for pass-through mode. */
296     if (!(en_s || en_g)) {
297         iotlb->translated_addr = iotlb->iova;
298         iotlb->addr_mask = ~TARGET_PAGE_MASK;
299         /* Allow R/W in pass-through mode */
300         iotlb->perm = IOMMU_RW;
301         return 0;
302     }
303 
304     /* S/G translation parameters. */
305     for (pass = 0; pass < 2; pass++) {
306         uint32_t sv_mode;
307 
308         sc[pass].step = 0;
309         if (pass ? (s->fctl & RISCV_IOMMU_FCTL_GXL) :
310             (ctx->tc & RISCV_IOMMU_DC_TC_SXL)) {
311             /* 32bit mode for GXL/SXL == 1 */
312             switch (pass ? gatp : satp) {
313             case RISCV_IOMMU_DC_IOHGATP_MODE_BARE:
314                 sc[pass].levels    = 0;
315                 sc[pass].ptidxbits = 0;
316                 sc[pass].ptesize   = 0;
317                 break;
318             case RISCV_IOMMU_DC_IOHGATP_MODE_SV32X4:
319                 sv_mode = pass ? RISCV_IOMMU_CAP_SV32X4 : RISCV_IOMMU_CAP_SV32;
320                 if (!(s->cap & sv_mode)) {
321                     return RISCV_IOMMU_FQ_CAUSE_DDT_MISCONFIGURED;
322                 }
323                 sc[pass].levels    = 2;
324                 sc[pass].ptidxbits = 10;
325                 sc[pass].ptesize   = 4;
326                 break;
327             default:
328                 return RISCV_IOMMU_FQ_CAUSE_DDT_MISCONFIGURED;
329             }
330         } else {
331             /* 64bit mode for GXL/SXL == 0 */
332             switch (pass ? gatp : satp) {
333             case RISCV_IOMMU_DC_IOHGATP_MODE_BARE:
334                 sc[pass].levels    = 0;
335                 sc[pass].ptidxbits = 0;
336                 sc[pass].ptesize   = 0;
337                 break;
338             case RISCV_IOMMU_DC_IOHGATP_MODE_SV39X4:
339                 sv_mode = pass ? RISCV_IOMMU_CAP_SV39X4 : RISCV_IOMMU_CAP_SV39;
340                 if (!(s->cap & sv_mode)) {
341                     return RISCV_IOMMU_FQ_CAUSE_DDT_MISCONFIGURED;
342                 }
343                 sc[pass].levels    = 3;
344                 sc[pass].ptidxbits = 9;
345                 sc[pass].ptesize   = 8;
346                 break;
347             case RISCV_IOMMU_DC_IOHGATP_MODE_SV48X4:
348                 sv_mode = pass ? RISCV_IOMMU_CAP_SV48X4 : RISCV_IOMMU_CAP_SV48;
349                 if (!(s->cap & sv_mode)) {
350                     return RISCV_IOMMU_FQ_CAUSE_DDT_MISCONFIGURED;
351                 }
352                 sc[pass].levels    = 4;
353                 sc[pass].ptidxbits = 9;
354                 sc[pass].ptesize   = 8;
355                 break;
356             case RISCV_IOMMU_DC_IOHGATP_MODE_SV57X4:
357                 sv_mode = pass ? RISCV_IOMMU_CAP_SV57X4 : RISCV_IOMMU_CAP_SV57;
358                 if (!(s->cap & sv_mode)) {
359                     return RISCV_IOMMU_FQ_CAUSE_DDT_MISCONFIGURED;
360                 }
361                 sc[pass].levels    = 5;
362                 sc[pass].ptidxbits = 9;
363                 sc[pass].ptesize   = 8;
364                 break;
365             default:
366                 return RISCV_IOMMU_FQ_CAUSE_DDT_MISCONFIGURED;
367             }
368         }
369     };
370 
371     /* S/G stages translation tables root pointers */
372     gatp = PPN_PHYS(get_field(ctx->gatp, RISCV_IOMMU_ATP_PPN_FIELD));
373     satp = PPN_PHYS(get_field(ctx->satp, RISCV_IOMMU_ATP_PPN_FIELD));
374     addr = (en_s && en_g) ? satp : iotlb->iova;
375     base = en_g ? gatp : satp;
376     pass = en_g ? G_STAGE : S_STAGE;
377 
378     do {
379         const unsigned widened = (pass && !sc[pass].step) ? 2 : 0;
380         const unsigned va_bits = widened + sc[pass].ptidxbits;
381         const unsigned va_skip = TARGET_PAGE_BITS + sc[pass].ptidxbits *
382                                  (sc[pass].levels - 1 - sc[pass].step);
383         const unsigned idx = (addr >> va_skip) & ((1 << va_bits) - 1);
384         const dma_addr_t pte_addr = base + idx * sc[pass].ptesize;
385         const bool ade =
386             ctx->tc & (pass ? RISCV_IOMMU_DC_TC_GADE : RISCV_IOMMU_DC_TC_SADE);
387 
388         /* Address range check before first level lookup */
389         if (!sc[pass].step) {
390             const uint64_t va_len = va_skip + va_bits;
391             const uint64_t va_mask = (1ULL << va_len) - 1;
392 
393             if (pass == S_STAGE && va_len > 32) {
394                 target_ulong mask, masked_msbs;
395 
396                 mask = (1L << (TARGET_LONG_BITS - (va_len - 1))) - 1;
397                 masked_msbs = (addr >> (va_len - 1)) & mask;
398 
399                 if (masked_msbs != 0 && masked_msbs != mask) {
400                     return (iotlb->perm & IOMMU_WO) ?
401                                 RISCV_IOMMU_FQ_CAUSE_WR_FAULT_S :
402                                 RISCV_IOMMU_FQ_CAUSE_RD_FAULT_S;
403                 }
404             } else {
405                 if ((addr & va_mask) != addr) {
406                     return (iotlb->perm & IOMMU_WO) ?
407                                 RISCV_IOMMU_FQ_CAUSE_WR_FAULT_VS :
408                                 RISCV_IOMMU_FQ_CAUSE_RD_FAULT_VS;
409                 }
410             }
411         }
412 
413 
414         if (pass == S_STAGE) {
415             riscv_iommu_hpm_incr_ctr(s, ctx, RISCV_IOMMU_HPMEVENT_S_VS_WALKS);
416         } else {
417             riscv_iommu_hpm_incr_ctr(s, ctx, RISCV_IOMMU_HPMEVENT_G_WALKS);
418         }
419 
420         /* Read page table entry */
421         if (sc[pass].ptesize == 4) {
422             uint32_t pte32 = 0;
423             ret = ldl_le_dma(s->target_as, pte_addr, &pte32,
424                              MEMTXATTRS_UNSPECIFIED);
425             pte = pte32;
426         } else {
427             ret = ldq_le_dma(s->target_as, pte_addr, &pte,
428                              MEMTXATTRS_UNSPECIFIED);
429         }
430         if (ret != MEMTX_OK) {
431             return (iotlb->perm & IOMMU_WO) ? RISCV_IOMMU_FQ_CAUSE_WR_FAULT
432                                             : RISCV_IOMMU_FQ_CAUSE_RD_FAULT;
433         }
434 
435         sc[pass].step++;
436         hwaddr ppn = pte >> PTE_PPN_SHIFT;
437 
438         if (!(pte & PTE_V)) {
439             break;                /* Invalid PTE */
440         } else if (!(pte & (PTE_R | PTE_W | PTE_X))) {
441             base = PPN_PHYS(ppn); /* Inner PTE, continue walking */
442         } else if ((pte & (PTE_R | PTE_W | PTE_X)) == PTE_W) {
443             break;                /* Reserved leaf PTE flags: PTE_W */
444         } else if ((pte & (PTE_R | PTE_W | PTE_X)) == (PTE_W | PTE_X)) {
445             break;                /* Reserved leaf PTE flags: PTE_W + PTE_X */
446         } else if (ppn & ((1ULL << (va_skip - TARGET_PAGE_BITS)) - 1)) {
447             break;                /* Misaligned PPN */
448         } else if ((iotlb->perm & IOMMU_RO) && !(pte & PTE_R)) {
449             break;                /* Read access check failed */
450         } else if ((iotlb->perm & IOMMU_WO) && !(pte & PTE_W)) {
451             break;                /* Write access check failed */
452         } else if ((iotlb->perm & IOMMU_RO) && !ade && !(pte & PTE_A)) {
453             break;                /* Access bit not set */
454         } else if ((iotlb->perm & IOMMU_WO) && !ade && !(pte & PTE_D)) {
455             break;                /* Dirty bit not set */
456         } else {
457             /* Leaf PTE, translation completed. */
458             sc[pass].step = sc[pass].levels;
459             base = PPN_PHYS(ppn) | (addr & ((1ULL << va_skip) - 1));
460             /* Update address mask based on smallest translation granularity */
461             iotlb->addr_mask &= (1ULL << va_skip) - 1;
462             /* Continue with S-Stage translation? */
463             if (pass && sc[0].step != sc[0].levels) {
464                 pass = S_STAGE;
465                 addr = iotlb->iova;
466                 continue;
467             }
468             /* Translation phase completed (GPA or SPA) */
469             iotlb->translated_addr = base;
470             iotlb->perm = (pte & PTE_W) ? ((pte & PTE_R) ? IOMMU_RW : IOMMU_WO)
471                                                          : IOMMU_RO;
472 
473             /* Check MSI GPA address match */
474             if (pass == S_STAGE && (iotlb->perm & IOMMU_WO) &&
475                 riscv_iommu_msi_check(s, ctx, base)) {
476                 /* Trap MSI writes and return GPA address. */
477                 iotlb->target_as = &s->trap_as;
478                 iotlb->addr_mask = ~TARGET_PAGE_MASK;
479                 return 0;
480             }
481 
482             /* Continue with G-Stage translation? */
483             if (!pass && en_g) {
484                 pass = G_STAGE;
485                 addr = base;
486                 base = gatp;
487                 sc[pass].step = 0;
488                 continue;
489             }
490 
491             return 0;
492         }
493 
494         if (sc[pass].step == sc[pass].levels) {
495             break; /* Can't find leaf PTE */
496         }
497 
498         /* Continue with G-Stage translation? */
499         if (!pass && en_g) {
500             pass = G_STAGE;
501             addr = base;
502             base = gatp;
503             sc[pass].step = 0;
504         }
505     } while (1);
506 
507     return (iotlb->perm & IOMMU_WO) ?
508                 (pass ? RISCV_IOMMU_FQ_CAUSE_WR_FAULT_VS :
509                         RISCV_IOMMU_FQ_CAUSE_WR_FAULT_S) :
510                 (pass ? RISCV_IOMMU_FQ_CAUSE_RD_FAULT_VS :
511                         RISCV_IOMMU_FQ_CAUSE_RD_FAULT_S);
512 }
513 
514 static void riscv_iommu_report_fault(RISCVIOMMUState *s,
515                                      RISCVIOMMUContext *ctx,
516                                      uint32_t fault_type, uint32_t cause,
517                                      bool pv,
518                                      uint64_t iotval, uint64_t iotval2)
519 {
520     struct riscv_iommu_fq_record ev = { 0 };
521 
522     if (ctx->tc & RISCV_IOMMU_DC_TC_DTF) {
523         switch (cause) {
524         case RISCV_IOMMU_FQ_CAUSE_DMA_DISABLED:
525         case RISCV_IOMMU_FQ_CAUSE_DDT_LOAD_FAULT:
526         case RISCV_IOMMU_FQ_CAUSE_DDT_INVALID:
527         case RISCV_IOMMU_FQ_CAUSE_DDT_MISCONFIGURED:
528         case RISCV_IOMMU_FQ_CAUSE_DDT_CORRUPTED:
529         case RISCV_IOMMU_FQ_CAUSE_INTERNAL_DP_ERROR:
530         case RISCV_IOMMU_FQ_CAUSE_MSI_WR_FAULT:
531             break;
532         default:
533             /* DTF prevents reporting a fault for this given cause */
534             return;
535         }
536     }
537 
538     ev.hdr = set_field(ev.hdr, RISCV_IOMMU_FQ_HDR_CAUSE, cause);
539     ev.hdr = set_field(ev.hdr, RISCV_IOMMU_FQ_HDR_TTYPE, fault_type);
540     ev.hdr = set_field(ev.hdr, RISCV_IOMMU_FQ_HDR_DID, ctx->devid);
541     ev.hdr = set_field(ev.hdr, RISCV_IOMMU_FQ_HDR_PV, true);
542 
543     if (pv) {
544         ev.hdr = set_field(ev.hdr, RISCV_IOMMU_FQ_HDR_PID, ctx->process_id);
545     }
546 
547     ev.iotval = iotval;
548     ev.iotval2 = iotval2;
549 
550     riscv_iommu_fault(s, &ev);
551 }
552 
553 /* Redirect MSI write for given GPA. */
554 static MemTxResult riscv_iommu_msi_write(RISCVIOMMUState *s,
555     RISCVIOMMUContext *ctx, uint64_t gpa, uint64_t data,
556     unsigned size, MemTxAttrs attrs)
557 {
558     MemTxResult res;
559     dma_addr_t addr;
560     uint64_t intn;
561     size_t offset;
562     uint32_t n190;
563     uint64_t pte[2];
564     int fault_type = RISCV_IOMMU_FQ_TTYPE_UADDR_WR;
565     int cause;
566 
567     /* Interrupt File Number */
568     intn = riscv_iommu_pext_u64(PPN_DOWN(gpa), ctx->msi_addr_mask);
569     offset = intn * sizeof(pte);
570 
571     /* fetch MSI PTE */
572     addr = PPN_PHYS(get_field(ctx->msiptp, RISCV_IOMMU_DC_MSIPTP_PPN));
573     if (addr & offset) {
574         /* Interrupt file number out of range */
575         res = MEMTX_ACCESS_ERROR;
576         cause = RISCV_IOMMU_FQ_CAUSE_MSI_LOAD_FAULT;
577         goto err;
578     }
579 
580     addr |= offset;
581     res = dma_memory_read(s->target_as, addr, &pte, sizeof(pte),
582             MEMTXATTRS_UNSPECIFIED);
583     if (res != MEMTX_OK) {
584         if (res == MEMTX_DECODE_ERROR) {
585             cause = RISCV_IOMMU_FQ_CAUSE_MSI_PT_CORRUPTED;
586         } else {
587             cause = RISCV_IOMMU_FQ_CAUSE_MSI_LOAD_FAULT;
588         }
589         goto err;
590     }
591 
592     le64_to_cpus(&pte[0]);
593     le64_to_cpus(&pte[1]);
594 
595     if (!(pte[0] & RISCV_IOMMU_MSI_PTE_V) || (pte[0] & RISCV_IOMMU_MSI_PTE_C)) {
596         /*
597          * The spec mentions that: "If msipte.C == 1, then further
598          * processing to interpret the PTE is implementation
599          * defined.". We'll abort with cause = 262 for this
600          * case too.
601          */
602         res = MEMTX_ACCESS_ERROR;
603         cause = RISCV_IOMMU_FQ_CAUSE_MSI_INVALID;
604         goto err;
605     }
606 
607     switch (get_field(pte[0], RISCV_IOMMU_MSI_PTE_M)) {
608     case RISCV_IOMMU_MSI_PTE_M_BASIC:
609         /* MSI Pass-through mode */
610         addr = PPN_PHYS(get_field(pte[0], RISCV_IOMMU_MSI_PTE_PPN));
611 
612         trace_riscv_iommu_msi(s->parent_obj.id, PCI_BUS_NUM(ctx->devid),
613                               PCI_SLOT(ctx->devid), PCI_FUNC(ctx->devid),
614                               gpa, addr);
615 
616         res = dma_memory_write(s->target_as, addr, &data, size, attrs);
617         if (res != MEMTX_OK) {
618             cause = RISCV_IOMMU_FQ_CAUSE_MSI_WR_FAULT;
619             goto err;
620         }
621 
622         return MEMTX_OK;
623     case RISCV_IOMMU_MSI_PTE_M_MRIF:
624         /* MRIF mode, continue. */
625         break;
626     default:
627         res = MEMTX_ACCESS_ERROR;
628         cause = RISCV_IOMMU_FQ_CAUSE_MSI_MISCONFIGURED;
629         goto err;
630     }
631 
632     /*
633      * Report an error for interrupt identities exceeding the maximum allowed
634      * for an IMSIC interrupt file (2047) or destination address is not 32-bit
635      * aligned. See IOMMU Specification, Chapter 2.3. MSI page tables.
636      */
637     if ((data > 2047) || (gpa & 3)) {
638         res = MEMTX_ACCESS_ERROR;
639         cause = RISCV_IOMMU_FQ_CAUSE_MSI_MISCONFIGURED;
640         goto err;
641     }
642 
643     /* MSI MRIF mode, non atomic pending bit update */
644 
645     /* MRIF pending bit address */
646     addr = get_field(pte[0], RISCV_IOMMU_MSI_PTE_MRIF_ADDR) << 9;
647     addr = addr | ((data & 0x7c0) >> 3);
648 
649     trace_riscv_iommu_msi(s->parent_obj.id, PCI_BUS_NUM(ctx->devid),
650                           PCI_SLOT(ctx->devid), PCI_FUNC(ctx->devid),
651                           gpa, addr);
652 
653     /* MRIF pending bit mask */
654     data = 1ULL << (data & 0x03f);
655     res = dma_memory_read(s->target_as, addr, &intn, sizeof(intn), attrs);
656     if (res != MEMTX_OK) {
657         cause = RISCV_IOMMU_FQ_CAUSE_MSI_LOAD_FAULT;
658         goto err;
659     }
660 
661     intn = intn | data;
662     res = dma_memory_write(s->target_as, addr, &intn, sizeof(intn), attrs);
663     if (res != MEMTX_OK) {
664         cause = RISCV_IOMMU_FQ_CAUSE_MSI_WR_FAULT;
665         goto err;
666     }
667 
668     /* Get MRIF enable bits */
669     addr = addr + sizeof(intn);
670     res = dma_memory_read(s->target_as, addr, &intn, sizeof(intn), attrs);
671     if (res != MEMTX_OK) {
672         cause = RISCV_IOMMU_FQ_CAUSE_MSI_LOAD_FAULT;
673         goto err;
674     }
675 
676     if (!(intn & data)) {
677         /* notification disabled, MRIF update completed. */
678         return MEMTX_OK;
679     }
680 
681     /* Send notification message */
682     addr = PPN_PHYS(get_field(pte[1], RISCV_IOMMU_MSI_MRIF_NPPN));
683     n190 = get_field(pte[1], RISCV_IOMMU_MSI_MRIF_NID) |
684           (get_field(pte[1], RISCV_IOMMU_MSI_MRIF_NID_MSB) << 10);
685 
686     res = dma_memory_write(s->target_as, addr, &n190, sizeof(n190), attrs);
687     if (res != MEMTX_OK) {
688         cause = RISCV_IOMMU_FQ_CAUSE_MSI_WR_FAULT;
689         goto err;
690     }
691 
692     trace_riscv_iommu_mrif_notification(s->parent_obj.id, n190, addr);
693 
694     return MEMTX_OK;
695 
696 err:
697     riscv_iommu_report_fault(s, ctx, fault_type, cause,
698                              !!ctx->process_id, 0, 0);
699     return res;
700 }
701 
702 /*
703  * Check device context configuration as described by the
704  * riscv-iommu spec section "Device-context configuration
705  * checks".
706  */
707 static bool riscv_iommu_validate_device_ctx(RISCVIOMMUState *s,
708                                             RISCVIOMMUContext *ctx)
709 {
710     uint32_t fsc_mode, msi_mode;
711     uint64_t gatp;
712 
713     if (!(s->cap & RISCV_IOMMU_CAP_ATS) &&
714         (ctx->tc & RISCV_IOMMU_DC_TC_EN_ATS ||
715          ctx->tc & RISCV_IOMMU_DC_TC_EN_PRI ||
716          ctx->tc & RISCV_IOMMU_DC_TC_PRPR)) {
717         return false;
718     }
719 
720     if (!(ctx->tc & RISCV_IOMMU_DC_TC_EN_ATS) &&
721         (ctx->tc & RISCV_IOMMU_DC_TC_T2GPA ||
722          ctx->tc & RISCV_IOMMU_DC_TC_EN_PRI)) {
723         return false;
724     }
725 
726     if (!(ctx->tc & RISCV_IOMMU_DC_TC_EN_PRI) &&
727         ctx->tc & RISCV_IOMMU_DC_TC_PRPR) {
728         return false;
729     }
730 
731     if (!(s->cap & RISCV_IOMMU_CAP_T2GPA) &&
732         ctx->tc & RISCV_IOMMU_DC_TC_T2GPA) {
733         return false;
734     }
735 
736     if (s->cap & RISCV_IOMMU_CAP_MSI_FLAT) {
737         msi_mode = get_field(ctx->msiptp, RISCV_IOMMU_DC_MSIPTP_MODE);
738 
739         if (msi_mode != RISCV_IOMMU_DC_MSIPTP_MODE_OFF &&
740             msi_mode != RISCV_IOMMU_DC_MSIPTP_MODE_FLAT) {
741             return false;
742         }
743     }
744 
745     gatp = get_field(ctx->gatp, RISCV_IOMMU_ATP_MODE_FIELD);
746     if (ctx->tc & RISCV_IOMMU_DC_TC_T2GPA &&
747         gatp == RISCV_IOMMU_DC_IOHGATP_MODE_BARE) {
748         return false;
749     }
750 
751     fsc_mode = get_field(ctx->satp, RISCV_IOMMU_DC_FSC_MODE);
752 
753     if (ctx->tc & RISCV_IOMMU_DC_TC_PDTV) {
754         switch (fsc_mode) {
755         case RISCV_IOMMU_DC_FSC_PDTP_MODE_PD8:
756             if (!(s->cap & RISCV_IOMMU_CAP_PD8)) {
757                 return false;
758             }
759             break;
760         case RISCV_IOMMU_DC_FSC_PDTP_MODE_PD17:
761             if (!(s->cap & RISCV_IOMMU_CAP_PD17)) {
762                 return false;
763             }
764             break;
765         case RISCV_IOMMU_DC_FSC_PDTP_MODE_PD20:
766             if (!(s->cap & RISCV_IOMMU_CAP_PD20)) {
767                 return false;
768             }
769             break;
770         }
771     } else {
772         /* DC.tc.PDTV is 0 */
773         if (ctx->tc & RISCV_IOMMU_DC_TC_DPE) {
774             return false;
775         }
776 
777         if (ctx->tc & RISCV_IOMMU_DC_TC_SXL) {
778             if (fsc_mode == RISCV_IOMMU_CAP_SV32 &&
779                 !(s->cap & RISCV_IOMMU_CAP_SV32)) {
780                 return false;
781             }
782         } else {
783             switch (fsc_mode) {
784             case RISCV_IOMMU_DC_FSC_IOSATP_MODE_SV39:
785                 if (!(s->cap & RISCV_IOMMU_CAP_SV39)) {
786                     return false;
787                 }
788                 break;
789             case RISCV_IOMMU_DC_FSC_IOSATP_MODE_SV48:
790                 if (!(s->cap & RISCV_IOMMU_CAP_SV48)) {
791                     return false;
792                 }
793             break;
794             case RISCV_IOMMU_DC_FSC_IOSATP_MODE_SV57:
795                 if (!(s->cap & RISCV_IOMMU_CAP_SV57)) {
796                     return false;
797                 }
798                 break;
799             }
800         }
801     }
802 
803     /*
804      * CAP_END is always zero (only one endianess). FCTL_BE is
805      * always zero (little-endian accesses). Thus TC_SBE must
806      * always be LE, i.e. zero.
807      */
808     if (ctx->tc & RISCV_IOMMU_DC_TC_SBE) {
809         return false;
810     }
811 
812     return true;
813 }
814 
815 /*
816  * Validate process context (PC) according to section
817  * "Process-context configuration checks".
818  */
819 static bool riscv_iommu_validate_process_ctx(RISCVIOMMUState *s,
820                                              RISCVIOMMUContext *ctx)
821 {
822     uint32_t mode;
823 
824     if (get_field(ctx->ta, RISCV_IOMMU_PC_TA_RESERVED)) {
825         return false;
826     }
827 
828     if (get_field(ctx->satp, RISCV_IOMMU_PC_FSC_RESERVED)) {
829         return false;
830     }
831 
832     mode = get_field(ctx->satp, RISCV_IOMMU_DC_FSC_MODE);
833     switch (mode) {
834     case RISCV_IOMMU_DC_FSC_MODE_BARE:
835     /* sv39 and sv32 modes have the same value (8) */
836     case RISCV_IOMMU_DC_FSC_IOSATP_MODE_SV39:
837     case RISCV_IOMMU_DC_FSC_IOSATP_MODE_SV48:
838     case RISCV_IOMMU_DC_FSC_IOSATP_MODE_SV57:
839         break;
840     default:
841         return false;
842     }
843 
844     if (ctx->tc & RISCV_IOMMU_DC_TC_SXL) {
845         if (mode == RISCV_IOMMU_DC_FSC_IOSATP_MODE_SV32 &&
846             !(s->cap & RISCV_IOMMU_CAP_SV32)) {
847                 return false;
848         }
849     } else {
850         switch (mode) {
851         case RISCV_IOMMU_DC_FSC_IOSATP_MODE_SV39:
852             if (!(s->cap & RISCV_IOMMU_CAP_SV39)) {
853                 return false;
854             }
855             break;
856         case RISCV_IOMMU_DC_FSC_IOSATP_MODE_SV48:
857             if (!(s->cap & RISCV_IOMMU_CAP_SV48)) {
858                 return false;
859             }
860             break;
861         case RISCV_IOMMU_DC_FSC_IOSATP_MODE_SV57:
862             if (!(s->cap & RISCV_IOMMU_CAP_SV57)) {
863                 return false;
864             }
865             break;
866         }
867     }
868 
869     return true;
870 }
871 
872 /*
873  * RISC-V IOMMU Device Context Loopkup - Device Directory Tree Walk
874  *
875  * @s         : IOMMU Device State
876  * @ctx       : Device Translation Context with devid and process_id set.
877  * @return    : success or fault code.
878  */
879 static int riscv_iommu_ctx_fetch(RISCVIOMMUState *s, RISCVIOMMUContext *ctx)
880 {
881     const uint64_t ddtp = s->ddtp;
882     unsigned mode = get_field(ddtp, RISCV_IOMMU_DDTP_MODE);
883     dma_addr_t addr = PPN_PHYS(get_field(ddtp, RISCV_IOMMU_DDTP_PPN));
884     struct riscv_iommu_dc dc;
885     /* Device Context format: 0: extended (64 bytes) | 1: base (32 bytes) */
886     const int dc_fmt = !s->enable_msi;
887     const size_t dc_len = sizeof(dc) >> dc_fmt;
888     int depth;
889     uint64_t de;
890 
891     switch (mode) {
892     case RISCV_IOMMU_DDTP_MODE_OFF:
893         return RISCV_IOMMU_FQ_CAUSE_DMA_DISABLED;
894 
895     case RISCV_IOMMU_DDTP_MODE_BARE:
896         /* mock up pass-through translation context */
897         ctx->gatp = set_field(0, RISCV_IOMMU_ATP_MODE_FIELD,
898             RISCV_IOMMU_DC_IOHGATP_MODE_BARE);
899         ctx->satp = set_field(0, RISCV_IOMMU_ATP_MODE_FIELD,
900             RISCV_IOMMU_DC_FSC_MODE_BARE);
901 
902         ctx->tc = RISCV_IOMMU_DC_TC_V;
903         if (s->enable_ats) {
904             ctx->tc |= RISCV_IOMMU_DC_TC_EN_ATS;
905         }
906 
907         ctx->ta = 0;
908         ctx->msiptp = 0;
909         return 0;
910 
911     case RISCV_IOMMU_DDTP_MODE_1LVL:
912         depth = 0;
913         break;
914 
915     case RISCV_IOMMU_DDTP_MODE_2LVL:
916         depth = 1;
917         break;
918 
919     case RISCV_IOMMU_DDTP_MODE_3LVL:
920         depth = 2;
921         break;
922 
923     default:
924         return RISCV_IOMMU_FQ_CAUSE_DDT_MISCONFIGURED;
925     }
926 
927     /*
928      * Check supported device id width (in bits).
929      * See IOMMU Specification, Chapter 6. Software guidelines.
930      * - if extended device-context format is used:
931      *   1LVL: 6, 2LVL: 15, 3LVL: 24
932      * - if base device-context format is used:
933      *   1LVL: 7, 2LVL: 16, 3LVL: 24
934      */
935     if (ctx->devid >= (1 << (depth * 9 + 6 + (dc_fmt && depth != 2)))) {
936         return RISCV_IOMMU_FQ_CAUSE_TTYPE_BLOCKED;
937     }
938 
939     /* Device directory tree walk */
940     for (; depth-- > 0; ) {
941         riscv_iommu_hpm_incr_ctr(s, ctx, RISCV_IOMMU_HPMEVENT_DD_WALK);
942         /*
943          * Select device id index bits based on device directory tree level
944          * and device context format.
945          * See IOMMU Specification, Chapter 2. Data Structures.
946          * - if extended device-context format is used:
947          *   device index: [23:15][14:6][5:0]
948          * - if base device-context format is used:
949          *   device index: [23:16][15:7][6:0]
950          */
951         const int split = depth * 9 + 6 + dc_fmt;
952         addr |= ((ctx->devid >> split) << 3) & ~TARGET_PAGE_MASK;
953         if (dma_memory_read(s->target_as, addr, &de, sizeof(de),
954                             MEMTXATTRS_UNSPECIFIED) != MEMTX_OK) {
955             return RISCV_IOMMU_FQ_CAUSE_DDT_LOAD_FAULT;
956         }
957         le64_to_cpus(&de);
958         if (!(de & RISCV_IOMMU_DDTE_VALID)) {
959             /* invalid directory entry */
960             return RISCV_IOMMU_FQ_CAUSE_DDT_INVALID;
961         }
962         if (de & ~(RISCV_IOMMU_DDTE_PPN | RISCV_IOMMU_DDTE_VALID)) {
963             /* reserved bits set */
964             return RISCV_IOMMU_FQ_CAUSE_DDT_MISCONFIGURED;
965         }
966         addr = PPN_PHYS(get_field(de, RISCV_IOMMU_DDTE_PPN));
967     }
968 
969     riscv_iommu_hpm_incr_ctr(s, ctx, RISCV_IOMMU_HPMEVENT_DD_WALK);
970 
971     /* index into device context entry page */
972     addr |= (ctx->devid * dc_len) & ~TARGET_PAGE_MASK;
973 
974     memset(&dc, 0, sizeof(dc));
975     if (dma_memory_read(s->target_as, addr, &dc, dc_len,
976                         MEMTXATTRS_UNSPECIFIED) != MEMTX_OK) {
977         return RISCV_IOMMU_FQ_CAUSE_DDT_LOAD_FAULT;
978     }
979 
980     /* Set translation context. */
981     ctx->tc = le64_to_cpu(dc.tc);
982     ctx->gatp = le64_to_cpu(dc.iohgatp);
983     ctx->satp = le64_to_cpu(dc.fsc);
984     ctx->ta = le64_to_cpu(dc.ta);
985     ctx->msiptp = le64_to_cpu(dc.msiptp);
986     ctx->msi_addr_mask = le64_to_cpu(dc.msi_addr_mask);
987     ctx->msi_addr_pattern = le64_to_cpu(dc.msi_addr_pattern);
988 
989     if (!(ctx->tc & RISCV_IOMMU_DC_TC_V)) {
990         return RISCV_IOMMU_FQ_CAUSE_DDT_INVALID;
991     }
992 
993     if (!riscv_iommu_validate_device_ctx(s, ctx)) {
994         return RISCV_IOMMU_FQ_CAUSE_DDT_MISCONFIGURED;
995     }
996 
997     /* FSC field checks */
998     mode = get_field(ctx->satp, RISCV_IOMMU_DC_FSC_MODE);
999     addr = PPN_PHYS(get_field(ctx->satp, RISCV_IOMMU_DC_FSC_PPN));
1000 
1001     if (!(ctx->tc & RISCV_IOMMU_DC_TC_PDTV)) {
1002         if (ctx->process_id != RISCV_IOMMU_NOPROCID) {
1003             /* PID is disabled */
1004             return RISCV_IOMMU_FQ_CAUSE_TTYPE_BLOCKED;
1005         }
1006         if (mode > RISCV_IOMMU_DC_FSC_IOSATP_MODE_SV57) {
1007             /* Invalid translation mode */
1008             return RISCV_IOMMU_FQ_CAUSE_DDT_INVALID;
1009         }
1010         return 0;
1011     }
1012 
1013     if (ctx->process_id == RISCV_IOMMU_NOPROCID) {
1014         if (!(ctx->tc & RISCV_IOMMU_DC_TC_DPE)) {
1015             /* No default process_id enabled, set BARE mode */
1016             ctx->satp = 0ULL;
1017             return 0;
1018         } else {
1019             /* Use default process_id #0 */
1020             ctx->process_id = 0;
1021         }
1022     }
1023 
1024     if (mode == RISCV_IOMMU_DC_FSC_MODE_BARE) {
1025         /* No S-Stage translation, done. */
1026         return 0;
1027     }
1028 
1029     /* FSC.TC.PDTV enabled */
1030     if (mode > RISCV_IOMMU_DC_FSC_PDTP_MODE_PD20) {
1031         /* Invalid PDTP.MODE */
1032         return RISCV_IOMMU_FQ_CAUSE_PDT_MISCONFIGURED;
1033     }
1034 
1035     for (depth = mode - RISCV_IOMMU_DC_FSC_PDTP_MODE_PD8; depth-- > 0; ) {
1036         riscv_iommu_hpm_incr_ctr(s, ctx, RISCV_IOMMU_HPMEVENT_PD_WALK);
1037 
1038         /*
1039          * Select process id index bits based on process directory tree
1040          * level. See IOMMU Specification, 2.2. Process-Directory-Table.
1041          */
1042         const int split = depth * 9 + 8;
1043         addr |= ((ctx->process_id >> split) << 3) & ~TARGET_PAGE_MASK;
1044         if (dma_memory_read(s->target_as, addr, &de, sizeof(de),
1045                             MEMTXATTRS_UNSPECIFIED) != MEMTX_OK) {
1046             return RISCV_IOMMU_FQ_CAUSE_PDT_LOAD_FAULT;
1047         }
1048         le64_to_cpus(&de);
1049         if (!(de & RISCV_IOMMU_PDTE_VALID)) {
1050             return RISCV_IOMMU_FQ_CAUSE_PDT_INVALID;
1051         }
1052         addr = PPN_PHYS(get_field(de, RISCV_IOMMU_PDTE_PPN));
1053     }
1054 
1055     riscv_iommu_hpm_incr_ctr(s, ctx, RISCV_IOMMU_HPMEVENT_PD_WALK);
1056 
1057     /* Leaf entry in PDT */
1058     addr |= (ctx->process_id << 4) & ~TARGET_PAGE_MASK;
1059     if (dma_memory_read(s->target_as, addr, &dc.ta, sizeof(uint64_t) * 2,
1060                         MEMTXATTRS_UNSPECIFIED) != MEMTX_OK) {
1061         return RISCV_IOMMU_FQ_CAUSE_PDT_LOAD_FAULT;
1062     }
1063 
1064     /* Use FSC and TA from process directory entry. */
1065     ctx->ta = le64_to_cpu(dc.ta);
1066     ctx->satp = le64_to_cpu(dc.fsc);
1067 
1068     if (!(ctx->ta & RISCV_IOMMU_PC_TA_V)) {
1069         return RISCV_IOMMU_FQ_CAUSE_PDT_INVALID;
1070     }
1071 
1072     if (!riscv_iommu_validate_process_ctx(s, ctx)) {
1073         return RISCV_IOMMU_FQ_CAUSE_PDT_MISCONFIGURED;
1074     }
1075 
1076     return 0;
1077 }
1078 
1079 /* Translation Context cache support */
1080 static gboolean riscv_iommu_ctx_equal(gconstpointer v1, gconstpointer v2)
1081 {
1082     RISCVIOMMUContext *c1 = (RISCVIOMMUContext *) v1;
1083     RISCVIOMMUContext *c2 = (RISCVIOMMUContext *) v2;
1084     return c1->devid == c2->devid &&
1085            c1->process_id == c2->process_id;
1086 }
1087 
1088 static guint riscv_iommu_ctx_hash(gconstpointer v)
1089 {
1090     RISCVIOMMUContext *ctx = (RISCVIOMMUContext *) v;
1091     /*
1092      * Generate simple hash of (process_id, devid)
1093      * assuming 24-bit wide devid.
1094      */
1095     return (guint)(ctx->devid) + ((guint)(ctx->process_id) << 24);
1096 }
1097 
1098 static void riscv_iommu_ctx_inval_devid_procid(gpointer key, gpointer value,
1099                                                gpointer data)
1100 {
1101     RISCVIOMMUContext *ctx = (RISCVIOMMUContext *) value;
1102     RISCVIOMMUContext *arg = (RISCVIOMMUContext *) data;
1103     if (ctx->tc & RISCV_IOMMU_DC_TC_V &&
1104         ctx->devid == arg->devid &&
1105         ctx->process_id == arg->process_id) {
1106         ctx->tc &= ~RISCV_IOMMU_DC_TC_V;
1107     }
1108 }
1109 
1110 static void riscv_iommu_ctx_inval_devid(gpointer key, gpointer value,
1111                                         gpointer data)
1112 {
1113     RISCVIOMMUContext *ctx = (RISCVIOMMUContext *) value;
1114     RISCVIOMMUContext *arg = (RISCVIOMMUContext *) data;
1115     if (ctx->tc & RISCV_IOMMU_DC_TC_V &&
1116         ctx->devid == arg->devid) {
1117         ctx->tc &= ~RISCV_IOMMU_DC_TC_V;
1118     }
1119 }
1120 
1121 static void riscv_iommu_ctx_inval_all(gpointer key, gpointer value,
1122                                       gpointer data)
1123 {
1124     RISCVIOMMUContext *ctx = (RISCVIOMMUContext *) value;
1125     if (ctx->tc & RISCV_IOMMU_DC_TC_V) {
1126         ctx->tc &= ~RISCV_IOMMU_DC_TC_V;
1127     }
1128 }
1129 
1130 static void riscv_iommu_ctx_inval(RISCVIOMMUState *s, GHFunc func,
1131                                   uint32_t devid, uint32_t process_id)
1132 {
1133     GHashTable *ctx_cache;
1134     RISCVIOMMUContext key = {
1135         .devid = devid,
1136         .process_id = process_id,
1137     };
1138     ctx_cache = g_hash_table_ref(s->ctx_cache);
1139     g_hash_table_foreach(ctx_cache, func, &key);
1140     g_hash_table_unref(ctx_cache);
1141 }
1142 
1143 /* Find or allocate translation context for a given {device_id, process_id} */
1144 static RISCVIOMMUContext *riscv_iommu_ctx(RISCVIOMMUState *s,
1145                                           unsigned devid, unsigned process_id,
1146                                           void **ref)
1147 {
1148     GHashTable *ctx_cache;
1149     RISCVIOMMUContext *ctx;
1150     RISCVIOMMUContext key = {
1151         .devid = devid,
1152         .process_id = process_id,
1153     };
1154 
1155     ctx_cache = g_hash_table_ref(s->ctx_cache);
1156     ctx = g_hash_table_lookup(ctx_cache, &key);
1157 
1158     if (ctx && (ctx->tc & RISCV_IOMMU_DC_TC_V)) {
1159         *ref = ctx_cache;
1160         return ctx;
1161     }
1162 
1163     ctx = g_new0(RISCVIOMMUContext, 1);
1164     ctx->devid = devid;
1165     ctx->process_id = process_id;
1166 
1167     int fault = riscv_iommu_ctx_fetch(s, ctx);
1168     if (!fault) {
1169         if (g_hash_table_size(ctx_cache) >= LIMIT_CACHE_CTX) {
1170             g_hash_table_unref(ctx_cache);
1171             ctx_cache = g_hash_table_new_full(riscv_iommu_ctx_hash,
1172                                               riscv_iommu_ctx_equal,
1173                                               g_free, NULL);
1174             g_hash_table_ref(ctx_cache);
1175             g_hash_table_unref(qatomic_xchg(&s->ctx_cache, ctx_cache));
1176         }
1177         g_hash_table_add(ctx_cache, ctx);
1178         *ref = ctx_cache;
1179         return ctx;
1180     }
1181 
1182     g_hash_table_unref(ctx_cache);
1183     *ref = NULL;
1184 
1185     riscv_iommu_report_fault(s, ctx, RISCV_IOMMU_FQ_TTYPE_UADDR_RD,
1186                              fault, !!process_id, 0, 0);
1187 
1188     g_free(ctx);
1189     return NULL;
1190 }
1191 
1192 static void riscv_iommu_ctx_put(RISCVIOMMUState *s, void *ref)
1193 {
1194     if (ref) {
1195         g_hash_table_unref((GHashTable *)ref);
1196     }
1197 }
1198 
1199 /* Find or allocate address space for a given device */
1200 static AddressSpace *riscv_iommu_space(RISCVIOMMUState *s, uint32_t devid)
1201 {
1202     RISCVIOMMUSpace *as;
1203 
1204     /* FIXME: PCIe bus remapping for attached endpoints. */
1205     devid |= s->bus << 8;
1206 
1207     QLIST_FOREACH(as, &s->spaces, list) {
1208         if (as->devid == devid) {
1209             break;
1210         }
1211     }
1212 
1213     if (as == NULL) {
1214         char name[64];
1215         as = g_new0(RISCVIOMMUSpace, 1);
1216 
1217         as->iommu = s;
1218         as->devid = devid;
1219 
1220         snprintf(name, sizeof(name), "riscv-iommu-%04x:%02x.%d-iova",
1221             PCI_BUS_NUM(as->devid), PCI_SLOT(as->devid), PCI_FUNC(as->devid));
1222 
1223         /* IOVA address space, untranslated addresses */
1224         memory_region_init_iommu(&as->iova_mr, sizeof(as->iova_mr),
1225             TYPE_RISCV_IOMMU_MEMORY_REGION,
1226             OBJECT(as), "riscv_iommu", UINT64_MAX);
1227         address_space_init(&as->iova_as, MEMORY_REGION(&as->iova_mr), name);
1228 
1229         QLIST_INSERT_HEAD(&s->spaces, as, list);
1230 
1231         trace_riscv_iommu_new(s->parent_obj.id, PCI_BUS_NUM(as->devid),
1232                 PCI_SLOT(as->devid), PCI_FUNC(as->devid));
1233     }
1234     return &as->iova_as;
1235 }
1236 
1237 /* Translation Object cache support */
1238 static gboolean riscv_iommu_iot_equal(gconstpointer v1, gconstpointer v2)
1239 {
1240     RISCVIOMMUEntry *t1 = (RISCVIOMMUEntry *) v1;
1241     RISCVIOMMUEntry *t2 = (RISCVIOMMUEntry *) v2;
1242     return t1->gscid == t2->gscid && t1->pscid == t2->pscid &&
1243            t1->iova == t2->iova && t1->tag == t2->tag;
1244 }
1245 
1246 static guint riscv_iommu_iot_hash(gconstpointer v)
1247 {
1248     RISCVIOMMUEntry *t = (RISCVIOMMUEntry *) v;
1249     return (guint)t->iova;
1250 }
1251 
1252 /* GV: 0 AV: 0 PSCV: 0 GVMA: 0 */
1253 /* GV: 0 AV: 0 GVMA: 1 */
1254 static
1255 void riscv_iommu_iot_inval_all(gpointer key, gpointer value, gpointer data)
1256 {
1257     RISCVIOMMUEntry *iot = (RISCVIOMMUEntry *) value;
1258     RISCVIOMMUEntry *arg = (RISCVIOMMUEntry *) data;
1259     if (iot->tag == arg->tag) {
1260         iot->perm = IOMMU_NONE;
1261     }
1262 }
1263 
1264 /* GV: 0 AV: 0 PSCV: 1 GVMA: 0 */
1265 static
1266 void riscv_iommu_iot_inval_pscid(gpointer key, gpointer value, gpointer data)
1267 {
1268     RISCVIOMMUEntry *iot = (RISCVIOMMUEntry *) value;
1269     RISCVIOMMUEntry *arg = (RISCVIOMMUEntry *) data;
1270     if (iot->tag == arg->tag &&
1271         iot->pscid == arg->pscid) {
1272         iot->perm = IOMMU_NONE;
1273     }
1274 }
1275 
1276 /* GV: 0 AV: 1 PSCV: 0 GVMA: 0 */
1277 static
1278 void riscv_iommu_iot_inval_iova(gpointer key, gpointer value, gpointer data)
1279 {
1280     RISCVIOMMUEntry *iot = (RISCVIOMMUEntry *) value;
1281     RISCVIOMMUEntry *arg = (RISCVIOMMUEntry *) data;
1282     if (iot->tag == arg->tag &&
1283         iot->iova == arg->iova) {
1284         iot->perm = IOMMU_NONE;
1285     }
1286 }
1287 
1288 /* GV: 0 AV: 1 PSCV: 1 GVMA: 0 */
1289 static void riscv_iommu_iot_inval_pscid_iova(gpointer key, gpointer value,
1290                                              gpointer data)
1291 {
1292     RISCVIOMMUEntry *iot = (RISCVIOMMUEntry *) value;
1293     RISCVIOMMUEntry *arg = (RISCVIOMMUEntry *) data;
1294     if (iot->tag == arg->tag &&
1295         iot->pscid == arg->pscid &&
1296         iot->iova == arg->iova) {
1297         iot->perm = IOMMU_NONE;
1298     }
1299 }
1300 
1301 /* GV: 1 AV: 0 PSCV: 0 GVMA: 0 */
1302 /* GV: 1 AV: 0 GVMA: 1 */
1303 static
1304 void riscv_iommu_iot_inval_gscid(gpointer key, gpointer value, gpointer data)
1305 {
1306     RISCVIOMMUEntry *iot = (RISCVIOMMUEntry *) value;
1307     RISCVIOMMUEntry *arg = (RISCVIOMMUEntry *) data;
1308     if (iot->tag == arg->tag &&
1309         iot->gscid == arg->gscid) {
1310         iot->perm = IOMMU_NONE;
1311     }
1312 }
1313 
1314 /* GV: 1 AV: 0 PSCV: 1 GVMA: 0 */
1315 static void riscv_iommu_iot_inval_gscid_pscid(gpointer key, gpointer value,
1316                                               gpointer data)
1317 {
1318     RISCVIOMMUEntry *iot = (RISCVIOMMUEntry *) value;
1319     RISCVIOMMUEntry *arg = (RISCVIOMMUEntry *) data;
1320     if (iot->tag == arg->tag &&
1321         iot->gscid == arg->gscid &&
1322         iot->pscid == arg->pscid) {
1323         iot->perm = IOMMU_NONE;
1324     }
1325 }
1326 
1327 /* GV: 1 AV: 1 PSCV: 0 GVMA: 0 */
1328 /* GV: 1 AV: 1 GVMA: 1 */
1329 static void riscv_iommu_iot_inval_gscid_iova(gpointer key, gpointer value,
1330                                              gpointer data)
1331 {
1332     RISCVIOMMUEntry *iot = (RISCVIOMMUEntry *) value;
1333     RISCVIOMMUEntry *arg = (RISCVIOMMUEntry *) data;
1334     if (iot->tag == arg->tag &&
1335         iot->gscid == arg->gscid &&
1336         iot->iova == arg->iova) {
1337         iot->perm = IOMMU_NONE;
1338     }
1339 }
1340 
1341 /* GV: 1 AV: 1 PSCV: 1 GVMA: 0 */
1342 static void riscv_iommu_iot_inval_gscid_pscid_iova(gpointer key, gpointer value,
1343                                                    gpointer data)
1344 {
1345     RISCVIOMMUEntry *iot = (RISCVIOMMUEntry *) value;
1346     RISCVIOMMUEntry *arg = (RISCVIOMMUEntry *) data;
1347     if (iot->tag == arg->tag &&
1348         iot->gscid == arg->gscid &&
1349         iot->pscid == arg->pscid &&
1350         iot->iova == arg->iova) {
1351         iot->perm = IOMMU_NONE;
1352     }
1353 }
1354 
1355 /* caller should keep ref-count for iot_cache object */
1356 static RISCVIOMMUEntry *riscv_iommu_iot_lookup(RISCVIOMMUContext *ctx,
1357     GHashTable *iot_cache, hwaddr iova, RISCVIOMMUTransTag transtag)
1358 {
1359     RISCVIOMMUEntry key = {
1360         .tag   = transtag,
1361         .gscid = get_field(ctx->gatp, RISCV_IOMMU_DC_IOHGATP_GSCID),
1362         .pscid = get_field(ctx->ta, RISCV_IOMMU_DC_TA_PSCID),
1363         .iova  = PPN_DOWN(iova),
1364     };
1365     return g_hash_table_lookup(iot_cache, &key);
1366 }
1367 
1368 /* caller should keep ref-count for iot_cache object */
1369 static void riscv_iommu_iot_update(RISCVIOMMUState *s,
1370     GHashTable *iot_cache, RISCVIOMMUEntry *iot)
1371 {
1372     if (!s->iot_limit) {
1373         return;
1374     }
1375 
1376     if (g_hash_table_size(s->iot_cache) >= s->iot_limit) {
1377         iot_cache = g_hash_table_new_full(riscv_iommu_iot_hash,
1378                                           riscv_iommu_iot_equal,
1379                                           g_free, NULL);
1380         g_hash_table_unref(qatomic_xchg(&s->iot_cache, iot_cache));
1381     }
1382     g_hash_table_add(iot_cache, iot);
1383 }
1384 
1385 static void riscv_iommu_iot_inval(RISCVIOMMUState *s, GHFunc func,
1386     uint32_t gscid, uint32_t pscid, hwaddr iova, RISCVIOMMUTransTag transtag)
1387 {
1388     GHashTable *iot_cache;
1389     RISCVIOMMUEntry key = {
1390         .tag = transtag,
1391         .gscid = gscid,
1392         .pscid = pscid,
1393         .iova  = PPN_DOWN(iova),
1394     };
1395 
1396     iot_cache = g_hash_table_ref(s->iot_cache);
1397     g_hash_table_foreach(iot_cache, func, &key);
1398     g_hash_table_unref(iot_cache);
1399 }
1400 
1401 static RISCVIOMMUTransTag riscv_iommu_get_transtag(RISCVIOMMUContext *ctx)
1402 {
1403     uint64_t satp = get_field(ctx->satp, RISCV_IOMMU_ATP_MODE_FIELD);
1404     uint64_t gatp = get_field(ctx->gatp, RISCV_IOMMU_ATP_MODE_FIELD);
1405 
1406     if (satp == RISCV_IOMMU_DC_FSC_MODE_BARE) {
1407         return (gatp == RISCV_IOMMU_DC_IOHGATP_MODE_BARE) ?
1408             RISCV_IOMMU_TRANS_TAG_BY : RISCV_IOMMU_TRANS_TAG_VG;
1409     } else {
1410         return (gatp == RISCV_IOMMU_DC_IOHGATP_MODE_BARE) ?
1411             RISCV_IOMMU_TRANS_TAG_SS : RISCV_IOMMU_TRANS_TAG_VN;
1412     }
1413 }
1414 
1415 static int riscv_iommu_translate(RISCVIOMMUState *s, RISCVIOMMUContext *ctx,
1416     IOMMUTLBEntry *iotlb, bool enable_cache)
1417 {
1418     RISCVIOMMUTransTag transtag = riscv_iommu_get_transtag(ctx);
1419     RISCVIOMMUEntry *iot;
1420     IOMMUAccessFlags perm;
1421     bool enable_pid;
1422     bool enable_pri;
1423     GHashTable *iot_cache;
1424     int fault;
1425 
1426     riscv_iommu_hpm_incr_ctr(s, ctx, RISCV_IOMMU_HPMEVENT_URQ);
1427 
1428     iot_cache = g_hash_table_ref(s->iot_cache);
1429     /*
1430      * TC[32] is reserved for custom extensions, used here to temporarily
1431      * enable automatic page-request generation for ATS queries.
1432      */
1433     enable_pri = (iotlb->perm == IOMMU_NONE) && (ctx->tc & BIT_ULL(32));
1434     enable_pid = (ctx->tc & RISCV_IOMMU_DC_TC_PDTV);
1435 
1436     /* Check for ATS request. */
1437     if (iotlb->perm == IOMMU_NONE) {
1438         riscv_iommu_hpm_incr_ctr(s, ctx, RISCV_IOMMU_HPMEVENT_ATS_RQ);
1439         /* Check if ATS is disabled. */
1440         if (!(ctx->tc & RISCV_IOMMU_DC_TC_EN_ATS)) {
1441             enable_pri = false;
1442             fault = RISCV_IOMMU_FQ_CAUSE_TTYPE_BLOCKED;
1443             goto done;
1444         }
1445     }
1446 
1447     iot = riscv_iommu_iot_lookup(ctx, iot_cache, iotlb->iova, transtag);
1448     perm = iot ? iot->perm : IOMMU_NONE;
1449     if (perm != IOMMU_NONE) {
1450         iotlb->translated_addr = PPN_PHYS(iot->phys);
1451         iotlb->addr_mask = ~TARGET_PAGE_MASK;
1452         iotlb->perm = perm;
1453         fault = 0;
1454         goto done;
1455     }
1456 
1457     riscv_iommu_hpm_incr_ctr(s, ctx, RISCV_IOMMU_HPMEVENT_TLB_MISS);
1458 
1459     /* Translate using device directory / page table information. */
1460     fault = riscv_iommu_spa_fetch(s, ctx, iotlb);
1461 
1462     if (!fault && iotlb->target_as == &s->trap_as) {
1463         /* Do not cache trapped MSI translations */
1464         goto done;
1465     }
1466 
1467     /*
1468      * We made an implementation choice to not cache identity-mapped
1469      * translations, as allowed by the specification, to avoid
1470      * translation cache evictions for other devices sharing the
1471      * IOMMU hardware model.
1472      */
1473     if (!fault && iotlb->translated_addr != iotlb->iova && enable_cache) {
1474         iot = g_new0(RISCVIOMMUEntry, 1);
1475         iot->iova = PPN_DOWN(iotlb->iova);
1476         iot->phys = PPN_DOWN(iotlb->translated_addr);
1477         iot->gscid = get_field(ctx->gatp, RISCV_IOMMU_DC_IOHGATP_GSCID);
1478         iot->pscid = get_field(ctx->ta, RISCV_IOMMU_DC_TA_PSCID);
1479         iot->perm = iotlb->perm;
1480         iot->tag = transtag;
1481         riscv_iommu_iot_update(s, iot_cache, iot);
1482     }
1483 
1484 done:
1485     g_hash_table_unref(iot_cache);
1486 
1487     if (enable_pri && fault) {
1488         struct riscv_iommu_pq_record pr = {0};
1489         if (enable_pid) {
1490             pr.hdr = set_field(RISCV_IOMMU_PREQ_HDR_PV,
1491                                RISCV_IOMMU_PREQ_HDR_PID, ctx->process_id);
1492         }
1493         pr.hdr = set_field(pr.hdr, RISCV_IOMMU_PREQ_HDR_DID, ctx->devid);
1494         pr.payload = (iotlb->iova & TARGET_PAGE_MASK) |
1495                      RISCV_IOMMU_PREQ_PAYLOAD_M;
1496         riscv_iommu_pri(s, &pr);
1497         return fault;
1498     }
1499 
1500     if (fault) {
1501         unsigned ttype = RISCV_IOMMU_FQ_TTYPE_PCIE_ATS_REQ;
1502 
1503         if (iotlb->perm & IOMMU_RW) {
1504             ttype = RISCV_IOMMU_FQ_TTYPE_UADDR_WR;
1505         } else if (iotlb->perm & IOMMU_RO) {
1506             ttype = RISCV_IOMMU_FQ_TTYPE_UADDR_RD;
1507         }
1508 
1509         riscv_iommu_report_fault(s, ctx, ttype, fault, enable_pid,
1510                                  iotlb->iova, iotlb->translated_addr);
1511         return fault;
1512     }
1513 
1514     return 0;
1515 }
1516 
1517 /* IOMMU Command Interface */
1518 static MemTxResult riscv_iommu_iofence(RISCVIOMMUState *s, bool notify,
1519     uint64_t addr, uint32_t data)
1520 {
1521     /*
1522      * ATS processing in this implementation of the IOMMU is synchronous,
1523      * no need to wait for completions here.
1524      */
1525     if (!notify) {
1526         return MEMTX_OK;
1527     }
1528 
1529     return dma_memory_write(s->target_as, addr, &data, sizeof(data),
1530         MEMTXATTRS_UNSPECIFIED);
1531 }
1532 
1533 static void riscv_iommu_ats(RISCVIOMMUState *s,
1534     struct riscv_iommu_command *cmd, IOMMUNotifierFlag flag,
1535     IOMMUAccessFlags perm,
1536     void (*trace_fn)(const char *id))
1537 {
1538     RISCVIOMMUSpace *as = NULL;
1539     IOMMUNotifier *n;
1540     IOMMUTLBEvent event;
1541     uint32_t pid;
1542     uint32_t devid;
1543     const bool pv = cmd->dword0 & RISCV_IOMMU_CMD_ATS_PV;
1544 
1545     if (cmd->dword0 & RISCV_IOMMU_CMD_ATS_DSV) {
1546         /* Use device segment and requester id */
1547         devid = get_field(cmd->dword0,
1548             RISCV_IOMMU_CMD_ATS_DSEG | RISCV_IOMMU_CMD_ATS_RID);
1549     } else {
1550         devid = get_field(cmd->dword0, RISCV_IOMMU_CMD_ATS_RID);
1551     }
1552 
1553     pid = get_field(cmd->dword0, RISCV_IOMMU_CMD_ATS_PID);
1554 
1555     QLIST_FOREACH(as, &s->spaces, list) {
1556         if (as->devid == devid) {
1557             break;
1558         }
1559     }
1560 
1561     if (!as || !as->notifier) {
1562         return;
1563     }
1564 
1565     event.type = flag;
1566     event.entry.perm = perm;
1567     event.entry.target_as = s->target_as;
1568 
1569     IOMMU_NOTIFIER_FOREACH(n, &as->iova_mr) {
1570         if (!pv || n->iommu_idx == pid) {
1571             event.entry.iova = n->start;
1572             event.entry.addr_mask = n->end - n->start;
1573             trace_fn(as->iova_mr.parent_obj.name);
1574             memory_region_notify_iommu_one(n, &event);
1575         }
1576     }
1577 }
1578 
1579 static void riscv_iommu_ats_inval(RISCVIOMMUState *s,
1580     struct riscv_iommu_command *cmd)
1581 {
1582     return riscv_iommu_ats(s, cmd, IOMMU_NOTIFIER_DEVIOTLB_UNMAP, IOMMU_NONE,
1583                            trace_riscv_iommu_ats_inval);
1584 }
1585 
1586 static void riscv_iommu_ats_prgr(RISCVIOMMUState *s,
1587     struct riscv_iommu_command *cmd)
1588 {
1589     unsigned resp_code = get_field(cmd->dword1,
1590                                    RISCV_IOMMU_CMD_ATS_PRGR_RESP_CODE);
1591 
1592     /* Using the access flag to carry response code information */
1593     IOMMUAccessFlags perm = resp_code ? IOMMU_NONE : IOMMU_RW;
1594     return riscv_iommu_ats(s, cmd, IOMMU_NOTIFIER_MAP, perm,
1595                            trace_riscv_iommu_ats_prgr);
1596 }
1597 
1598 static void riscv_iommu_process_ddtp(RISCVIOMMUState *s)
1599 {
1600     uint64_t old_ddtp = s->ddtp;
1601     uint64_t new_ddtp = riscv_iommu_reg_get64(s, RISCV_IOMMU_REG_DDTP);
1602     unsigned new_mode = get_field(new_ddtp, RISCV_IOMMU_DDTP_MODE);
1603     unsigned old_mode = get_field(old_ddtp, RISCV_IOMMU_DDTP_MODE);
1604     bool ok = false;
1605 
1606     /*
1607      * Check for allowed DDTP.MODE transitions:
1608      * {OFF, BARE}        -> {OFF, BARE, 1LVL, 2LVL, 3LVL}
1609      * {1LVL, 2LVL, 3LVL} -> {OFF, BARE}
1610      */
1611     if (new_mode == old_mode ||
1612         new_mode == RISCV_IOMMU_DDTP_MODE_OFF ||
1613         new_mode == RISCV_IOMMU_DDTP_MODE_BARE) {
1614         ok = true;
1615     } else if (new_mode == RISCV_IOMMU_DDTP_MODE_1LVL ||
1616                new_mode == RISCV_IOMMU_DDTP_MODE_2LVL ||
1617                new_mode == RISCV_IOMMU_DDTP_MODE_3LVL) {
1618         ok = old_mode == RISCV_IOMMU_DDTP_MODE_OFF ||
1619              old_mode == RISCV_IOMMU_DDTP_MODE_BARE;
1620     }
1621 
1622     if (ok) {
1623         /* clear reserved and busy bits, report back sanitized version */
1624         new_ddtp = set_field(new_ddtp & RISCV_IOMMU_DDTP_PPN,
1625                              RISCV_IOMMU_DDTP_MODE, new_mode);
1626     } else {
1627         new_ddtp = old_ddtp;
1628     }
1629     s->ddtp = new_ddtp;
1630 
1631     riscv_iommu_reg_set64(s, RISCV_IOMMU_REG_DDTP, new_ddtp);
1632 }
1633 
1634 /* Command function and opcode field. */
1635 #define RISCV_IOMMU_CMD(func, op) (((func) << 7) | (op))
1636 
1637 static void riscv_iommu_process_cq_tail(RISCVIOMMUState *s)
1638 {
1639     struct riscv_iommu_command cmd;
1640     MemTxResult res;
1641     dma_addr_t addr;
1642     uint32_t tail, head, ctrl;
1643     uint64_t cmd_opcode;
1644     GHFunc func;
1645 
1646     ctrl = riscv_iommu_reg_get32(s, RISCV_IOMMU_REG_CQCSR);
1647     tail = riscv_iommu_reg_get32(s, RISCV_IOMMU_REG_CQT) & s->cq_mask;
1648     head = riscv_iommu_reg_get32(s, RISCV_IOMMU_REG_CQH) & s->cq_mask;
1649 
1650     /* Check for pending error or queue processing disabled */
1651     if (!(ctrl & RISCV_IOMMU_CQCSR_CQON) ||
1652         !!(ctrl & (RISCV_IOMMU_CQCSR_CMD_ILL | RISCV_IOMMU_CQCSR_CQMF))) {
1653         return;
1654     }
1655 
1656     while (tail != head) {
1657         addr = s->cq_addr  + head * sizeof(cmd);
1658         res = dma_memory_read(s->target_as, addr, &cmd, sizeof(cmd),
1659                               MEMTXATTRS_UNSPECIFIED);
1660 
1661         if (res != MEMTX_OK) {
1662             riscv_iommu_reg_mod32(s, RISCV_IOMMU_REG_CQCSR,
1663                                   RISCV_IOMMU_CQCSR_CQMF, 0);
1664             goto fault;
1665         }
1666 
1667         trace_riscv_iommu_cmd(s->parent_obj.id, cmd.dword0, cmd.dword1);
1668 
1669         cmd_opcode = get_field(cmd.dword0,
1670                                RISCV_IOMMU_CMD_OPCODE | RISCV_IOMMU_CMD_FUNC);
1671 
1672         switch (cmd_opcode) {
1673         case RISCV_IOMMU_CMD(RISCV_IOMMU_CMD_IOFENCE_FUNC_C,
1674                              RISCV_IOMMU_CMD_IOFENCE_OPCODE):
1675             res = riscv_iommu_iofence(s,
1676                 cmd.dword0 & RISCV_IOMMU_CMD_IOFENCE_AV, cmd.dword1 << 2,
1677                 get_field(cmd.dword0, RISCV_IOMMU_CMD_IOFENCE_DATA));
1678 
1679             if (res != MEMTX_OK) {
1680                 riscv_iommu_reg_mod32(s, RISCV_IOMMU_REG_CQCSR,
1681                                       RISCV_IOMMU_CQCSR_CQMF, 0);
1682                 goto fault;
1683             }
1684             break;
1685 
1686         case RISCV_IOMMU_CMD(RISCV_IOMMU_CMD_IOTINVAL_FUNC_GVMA,
1687                              RISCV_IOMMU_CMD_IOTINVAL_OPCODE):
1688         {
1689             bool gv = !!(cmd.dword0 & RISCV_IOMMU_CMD_IOTINVAL_GV);
1690             bool av = !!(cmd.dword0 & RISCV_IOMMU_CMD_IOTINVAL_AV);
1691             bool pscv = !!(cmd.dword0 & RISCV_IOMMU_CMD_IOTINVAL_PSCV);
1692             uint32_t gscid = get_field(cmd.dword0,
1693                                        RISCV_IOMMU_CMD_IOTINVAL_GSCID);
1694             uint32_t pscid = get_field(cmd.dword0,
1695                                        RISCV_IOMMU_CMD_IOTINVAL_PSCID);
1696             hwaddr iova = (cmd.dword1 << 2) & TARGET_PAGE_MASK;
1697 
1698             if (pscv) {
1699                 /* illegal command arguments IOTINVAL.GVMA & PSCV == 1 */
1700                 goto cmd_ill;
1701             }
1702 
1703             func = riscv_iommu_iot_inval_all;
1704 
1705             if (gv) {
1706                 func = (av) ? riscv_iommu_iot_inval_gscid_iova :
1707                               riscv_iommu_iot_inval_gscid;
1708             }
1709 
1710             riscv_iommu_iot_inval(
1711                 s, func, gscid, pscid, iova, RISCV_IOMMU_TRANS_TAG_VG);
1712 
1713             riscv_iommu_iot_inval(
1714                 s, func, gscid, pscid, iova, RISCV_IOMMU_TRANS_TAG_VN);
1715             break;
1716         }
1717 
1718         case RISCV_IOMMU_CMD(RISCV_IOMMU_CMD_IOTINVAL_FUNC_VMA,
1719                              RISCV_IOMMU_CMD_IOTINVAL_OPCODE):
1720         {
1721             bool gv = !!(cmd.dword0 & RISCV_IOMMU_CMD_IOTINVAL_GV);
1722             bool av = !!(cmd.dword0 & RISCV_IOMMU_CMD_IOTINVAL_AV);
1723             bool pscv = !!(cmd.dword0 & RISCV_IOMMU_CMD_IOTINVAL_PSCV);
1724             uint32_t gscid = get_field(cmd.dword0,
1725                                        RISCV_IOMMU_CMD_IOTINVAL_GSCID);
1726             uint32_t pscid = get_field(cmd.dword0,
1727                                        RISCV_IOMMU_CMD_IOTINVAL_PSCID);
1728             hwaddr iova = (cmd.dword1 << 2) & TARGET_PAGE_MASK;
1729             RISCVIOMMUTransTag transtag;
1730 
1731             if (gv) {
1732                 transtag = RISCV_IOMMU_TRANS_TAG_VN;
1733                 if (pscv) {
1734                     func = (av) ? riscv_iommu_iot_inval_gscid_pscid_iova :
1735                                   riscv_iommu_iot_inval_gscid_pscid;
1736                 } else {
1737                     func = (av) ? riscv_iommu_iot_inval_gscid_iova :
1738                                   riscv_iommu_iot_inval_gscid;
1739                 }
1740             } else {
1741                 transtag = RISCV_IOMMU_TRANS_TAG_SS;
1742                 if (pscv) {
1743                     func = (av) ? riscv_iommu_iot_inval_pscid_iova :
1744                                   riscv_iommu_iot_inval_pscid;
1745                 } else {
1746                     func = (av) ? riscv_iommu_iot_inval_iova :
1747                                   riscv_iommu_iot_inval_all;
1748                 }
1749             }
1750 
1751             riscv_iommu_iot_inval(s, func, gscid, pscid, iova, transtag);
1752             break;
1753         }
1754 
1755         case RISCV_IOMMU_CMD(RISCV_IOMMU_CMD_IODIR_FUNC_INVAL_DDT,
1756                              RISCV_IOMMU_CMD_IODIR_OPCODE):
1757             if (!(cmd.dword0 & RISCV_IOMMU_CMD_IODIR_DV)) {
1758                 /* invalidate all device context cache mappings */
1759                 func = riscv_iommu_ctx_inval_all;
1760             } else {
1761                 /* invalidate all device context matching DID */
1762                 func = riscv_iommu_ctx_inval_devid;
1763             }
1764             riscv_iommu_ctx_inval(s, func,
1765                 get_field(cmd.dword0, RISCV_IOMMU_CMD_IODIR_DID), 0);
1766             break;
1767 
1768         case RISCV_IOMMU_CMD(RISCV_IOMMU_CMD_IODIR_FUNC_INVAL_PDT,
1769                              RISCV_IOMMU_CMD_IODIR_OPCODE):
1770             if (!(cmd.dword0 & RISCV_IOMMU_CMD_IODIR_DV)) {
1771                 /* illegal command arguments IODIR_PDT & DV == 0 */
1772                 goto cmd_ill;
1773             } else {
1774                 func = riscv_iommu_ctx_inval_devid_procid;
1775             }
1776             riscv_iommu_ctx_inval(s, func,
1777                 get_field(cmd.dword0, RISCV_IOMMU_CMD_IODIR_DID),
1778                 get_field(cmd.dword0, RISCV_IOMMU_CMD_IODIR_PID));
1779             break;
1780 
1781         /* ATS commands */
1782         case RISCV_IOMMU_CMD(RISCV_IOMMU_CMD_ATS_FUNC_INVAL,
1783                              RISCV_IOMMU_CMD_ATS_OPCODE):
1784             if (!s->enable_ats) {
1785                 goto cmd_ill;
1786             }
1787 
1788             riscv_iommu_ats_inval(s, &cmd);
1789             break;
1790 
1791         case RISCV_IOMMU_CMD(RISCV_IOMMU_CMD_ATS_FUNC_PRGR,
1792                              RISCV_IOMMU_CMD_ATS_OPCODE):
1793             if (!s->enable_ats) {
1794                 goto cmd_ill;
1795             }
1796 
1797             riscv_iommu_ats_prgr(s, &cmd);
1798             break;
1799 
1800         default:
1801         cmd_ill:
1802             /* Invalid instruction, do not advance instruction index. */
1803             riscv_iommu_reg_mod32(s, RISCV_IOMMU_REG_CQCSR,
1804                 RISCV_IOMMU_CQCSR_CMD_ILL, 0);
1805             goto fault;
1806         }
1807 
1808         /* Advance and update head pointer after command completes. */
1809         head = (head + 1) & s->cq_mask;
1810         riscv_iommu_reg_set32(s, RISCV_IOMMU_REG_CQH, head);
1811     }
1812     return;
1813 
1814 fault:
1815     if (ctrl & RISCV_IOMMU_CQCSR_CIE) {
1816         riscv_iommu_notify(s, RISCV_IOMMU_INTR_CQ);
1817     }
1818 }
1819 
1820 static void riscv_iommu_process_cq_control(RISCVIOMMUState *s)
1821 {
1822     uint64_t base;
1823     uint32_t ctrl_set = riscv_iommu_reg_get32(s, RISCV_IOMMU_REG_CQCSR);
1824     uint32_t ctrl_clr;
1825     bool enable = !!(ctrl_set & RISCV_IOMMU_CQCSR_CQEN);
1826     bool active = !!(ctrl_set & RISCV_IOMMU_CQCSR_CQON);
1827 
1828     if (enable && !active) {
1829         base = riscv_iommu_reg_get64(s, RISCV_IOMMU_REG_CQB);
1830         s->cq_mask = (2ULL << get_field(base, RISCV_IOMMU_CQB_LOG2SZ)) - 1;
1831         s->cq_addr = PPN_PHYS(get_field(base, RISCV_IOMMU_CQB_PPN));
1832         stl_le_p(&s->regs_ro[RISCV_IOMMU_REG_CQT], ~s->cq_mask);
1833         stl_le_p(&s->regs_rw[RISCV_IOMMU_REG_CQH], 0);
1834         stl_le_p(&s->regs_rw[RISCV_IOMMU_REG_CQT], 0);
1835         ctrl_set = RISCV_IOMMU_CQCSR_CQON;
1836         ctrl_clr = RISCV_IOMMU_CQCSR_BUSY | RISCV_IOMMU_CQCSR_CQMF |
1837                    RISCV_IOMMU_CQCSR_CMD_ILL | RISCV_IOMMU_CQCSR_CMD_TO |
1838                    RISCV_IOMMU_CQCSR_FENCE_W_IP;
1839     } else if (!enable && active) {
1840         stl_le_p(&s->regs_ro[RISCV_IOMMU_REG_CQT], ~0);
1841         ctrl_set = 0;
1842         ctrl_clr = RISCV_IOMMU_CQCSR_BUSY | RISCV_IOMMU_CQCSR_CQON;
1843     } else {
1844         ctrl_set = 0;
1845         ctrl_clr = RISCV_IOMMU_CQCSR_BUSY;
1846     }
1847 
1848     riscv_iommu_reg_mod32(s, RISCV_IOMMU_REG_CQCSR, ctrl_set, ctrl_clr);
1849 }
1850 
1851 static void riscv_iommu_process_fq_control(RISCVIOMMUState *s)
1852 {
1853     uint64_t base;
1854     uint32_t ctrl_set = riscv_iommu_reg_get32(s, RISCV_IOMMU_REG_FQCSR);
1855     uint32_t ctrl_clr;
1856     bool enable = !!(ctrl_set & RISCV_IOMMU_FQCSR_FQEN);
1857     bool active = !!(ctrl_set & RISCV_IOMMU_FQCSR_FQON);
1858 
1859     if (enable && !active) {
1860         base = riscv_iommu_reg_get64(s, RISCV_IOMMU_REG_FQB);
1861         s->fq_mask = (2ULL << get_field(base, RISCV_IOMMU_FQB_LOG2SZ)) - 1;
1862         s->fq_addr = PPN_PHYS(get_field(base, RISCV_IOMMU_FQB_PPN));
1863         stl_le_p(&s->regs_ro[RISCV_IOMMU_REG_FQH], ~s->fq_mask);
1864         stl_le_p(&s->regs_rw[RISCV_IOMMU_REG_FQH], 0);
1865         stl_le_p(&s->regs_rw[RISCV_IOMMU_REG_FQT], 0);
1866         ctrl_set = RISCV_IOMMU_FQCSR_FQON;
1867         ctrl_clr = RISCV_IOMMU_FQCSR_BUSY | RISCV_IOMMU_FQCSR_FQMF |
1868             RISCV_IOMMU_FQCSR_FQOF;
1869     } else if (!enable && active) {
1870         stl_le_p(&s->regs_ro[RISCV_IOMMU_REG_FQH], ~0);
1871         ctrl_set = 0;
1872         ctrl_clr = RISCV_IOMMU_FQCSR_BUSY | RISCV_IOMMU_FQCSR_FQON;
1873     } else {
1874         ctrl_set = 0;
1875         ctrl_clr = RISCV_IOMMU_FQCSR_BUSY;
1876     }
1877 
1878     riscv_iommu_reg_mod32(s, RISCV_IOMMU_REG_FQCSR, ctrl_set, ctrl_clr);
1879 }
1880 
1881 static void riscv_iommu_process_pq_control(RISCVIOMMUState *s)
1882 {
1883     uint64_t base;
1884     uint32_t ctrl_set = riscv_iommu_reg_get32(s, RISCV_IOMMU_REG_PQCSR);
1885     uint32_t ctrl_clr;
1886     bool enable = !!(ctrl_set & RISCV_IOMMU_PQCSR_PQEN);
1887     bool active = !!(ctrl_set & RISCV_IOMMU_PQCSR_PQON);
1888 
1889     if (enable && !active) {
1890         base = riscv_iommu_reg_get64(s, RISCV_IOMMU_REG_PQB);
1891         s->pq_mask = (2ULL << get_field(base, RISCV_IOMMU_PQB_LOG2SZ)) - 1;
1892         s->pq_addr = PPN_PHYS(get_field(base, RISCV_IOMMU_PQB_PPN));
1893         stl_le_p(&s->regs_ro[RISCV_IOMMU_REG_PQH], ~s->pq_mask);
1894         stl_le_p(&s->regs_rw[RISCV_IOMMU_REG_PQH], 0);
1895         stl_le_p(&s->regs_rw[RISCV_IOMMU_REG_PQT], 0);
1896         ctrl_set = RISCV_IOMMU_PQCSR_PQON;
1897         ctrl_clr = RISCV_IOMMU_PQCSR_BUSY | RISCV_IOMMU_PQCSR_PQMF |
1898             RISCV_IOMMU_PQCSR_PQOF;
1899     } else if (!enable && active) {
1900         stl_le_p(&s->regs_ro[RISCV_IOMMU_REG_PQH], ~0);
1901         ctrl_set = 0;
1902         ctrl_clr = RISCV_IOMMU_PQCSR_BUSY | RISCV_IOMMU_PQCSR_PQON;
1903     } else {
1904         ctrl_set = 0;
1905         ctrl_clr = RISCV_IOMMU_PQCSR_BUSY;
1906     }
1907 
1908     riscv_iommu_reg_mod32(s, RISCV_IOMMU_REG_PQCSR, ctrl_set, ctrl_clr);
1909 }
1910 
1911 static void riscv_iommu_process_dbg(RISCVIOMMUState *s)
1912 {
1913     uint64_t iova = riscv_iommu_reg_get64(s, RISCV_IOMMU_REG_TR_REQ_IOVA);
1914     uint64_t ctrl = riscv_iommu_reg_get64(s, RISCV_IOMMU_REG_TR_REQ_CTL);
1915     unsigned devid = get_field(ctrl, RISCV_IOMMU_TR_REQ_CTL_DID);
1916     unsigned pid = get_field(ctrl, RISCV_IOMMU_TR_REQ_CTL_PID);
1917     RISCVIOMMUContext *ctx;
1918     void *ref;
1919 
1920     if (!(ctrl & RISCV_IOMMU_TR_REQ_CTL_GO_BUSY)) {
1921         return;
1922     }
1923 
1924     ctx = riscv_iommu_ctx(s, devid, pid, &ref);
1925     if (ctx == NULL) {
1926         riscv_iommu_reg_set64(s, RISCV_IOMMU_REG_TR_RESPONSE,
1927                                  RISCV_IOMMU_TR_RESPONSE_FAULT |
1928                                  (RISCV_IOMMU_FQ_CAUSE_DMA_DISABLED << 10));
1929     } else {
1930         IOMMUTLBEntry iotlb = {
1931             .iova = iova,
1932             .perm = ctrl & RISCV_IOMMU_TR_REQ_CTL_NW ? IOMMU_RO : IOMMU_RW,
1933             .addr_mask = ~0,
1934             .target_as = NULL,
1935         };
1936         int fault = riscv_iommu_translate(s, ctx, &iotlb, false);
1937         if (fault) {
1938             iova = RISCV_IOMMU_TR_RESPONSE_FAULT | (((uint64_t) fault) << 10);
1939         } else {
1940             iova = iotlb.translated_addr & ~iotlb.addr_mask;
1941             iova = set_field(0, RISCV_IOMMU_TR_RESPONSE_PPN, PPN_DOWN(iova));
1942         }
1943         riscv_iommu_reg_set64(s, RISCV_IOMMU_REG_TR_RESPONSE, iova);
1944     }
1945 
1946     riscv_iommu_reg_mod64(s, RISCV_IOMMU_REG_TR_REQ_CTL, 0,
1947         RISCV_IOMMU_TR_REQ_CTL_GO_BUSY);
1948     riscv_iommu_ctx_put(s, ref);
1949 }
1950 
1951 typedef void riscv_iommu_process_fn(RISCVIOMMUState *s);
1952 
1953 static void riscv_iommu_update_icvec(RISCVIOMMUState *s, uint64_t data)
1954 {
1955     uint64_t icvec = 0;
1956 
1957     icvec |= MIN(data & RISCV_IOMMU_ICVEC_CIV,
1958                  s->icvec_avail_vectors & RISCV_IOMMU_ICVEC_CIV);
1959 
1960     icvec |= MIN(data & RISCV_IOMMU_ICVEC_FIV,
1961                  s->icvec_avail_vectors & RISCV_IOMMU_ICVEC_FIV);
1962 
1963     icvec |= MIN(data & RISCV_IOMMU_ICVEC_PMIV,
1964                  s->icvec_avail_vectors & RISCV_IOMMU_ICVEC_PMIV);
1965 
1966     icvec |= MIN(data & RISCV_IOMMU_ICVEC_PIV,
1967                  s->icvec_avail_vectors & RISCV_IOMMU_ICVEC_PIV);
1968 
1969     trace_riscv_iommu_icvec_write(data, icvec);
1970 
1971     riscv_iommu_reg_set64(s, RISCV_IOMMU_REG_ICVEC, icvec);
1972 }
1973 
1974 static void riscv_iommu_update_ipsr(RISCVIOMMUState *s, uint64_t data)
1975 {
1976     uint32_t cqcsr, fqcsr, pqcsr;
1977     uint32_t ipsr_set = 0;
1978     uint32_t ipsr_clr = 0;
1979 
1980     if (data & RISCV_IOMMU_IPSR_CIP) {
1981         cqcsr = riscv_iommu_reg_get32(s, RISCV_IOMMU_REG_CQCSR);
1982 
1983         if (cqcsr & RISCV_IOMMU_CQCSR_CIE &&
1984             (cqcsr & RISCV_IOMMU_CQCSR_FENCE_W_IP ||
1985              cqcsr & RISCV_IOMMU_CQCSR_CMD_ILL ||
1986              cqcsr & RISCV_IOMMU_CQCSR_CMD_TO ||
1987              cqcsr & RISCV_IOMMU_CQCSR_CQMF)) {
1988             ipsr_set |= RISCV_IOMMU_IPSR_CIP;
1989         } else {
1990             ipsr_clr |= RISCV_IOMMU_IPSR_CIP;
1991         }
1992     } else {
1993         ipsr_clr |= RISCV_IOMMU_IPSR_CIP;
1994     }
1995 
1996     if (data & RISCV_IOMMU_IPSR_FIP) {
1997         fqcsr = riscv_iommu_reg_get32(s, RISCV_IOMMU_REG_FQCSR);
1998 
1999         if (fqcsr & RISCV_IOMMU_FQCSR_FIE &&
2000             (fqcsr & RISCV_IOMMU_FQCSR_FQOF ||
2001              fqcsr & RISCV_IOMMU_FQCSR_FQMF)) {
2002             ipsr_set |= RISCV_IOMMU_IPSR_FIP;
2003         } else {
2004             ipsr_clr |= RISCV_IOMMU_IPSR_FIP;
2005         }
2006     } else {
2007         ipsr_clr |= RISCV_IOMMU_IPSR_FIP;
2008     }
2009 
2010     if (data & RISCV_IOMMU_IPSR_PIP) {
2011         pqcsr = riscv_iommu_reg_get32(s, RISCV_IOMMU_REG_PQCSR);
2012 
2013         if (pqcsr & RISCV_IOMMU_PQCSR_PIE &&
2014             (pqcsr & RISCV_IOMMU_PQCSR_PQOF ||
2015              pqcsr & RISCV_IOMMU_PQCSR_PQMF)) {
2016             ipsr_set |= RISCV_IOMMU_IPSR_PIP;
2017         } else {
2018             ipsr_clr |= RISCV_IOMMU_IPSR_PIP;
2019         }
2020     } else {
2021         ipsr_clr |= RISCV_IOMMU_IPSR_PIP;
2022     }
2023 
2024     riscv_iommu_reg_mod32(s, RISCV_IOMMU_REG_IPSR, ipsr_set, ipsr_clr);
2025 }
2026 
2027 static void riscv_iommu_process_hpm_writes(RISCVIOMMUState *s,
2028                                            uint32_t regb,
2029                                            bool prev_cy_inh)
2030 {
2031     switch (regb) {
2032     case RISCV_IOMMU_REG_IOCOUNTINH:
2033         riscv_iommu_process_iocntinh_cy(s, prev_cy_inh);
2034         break;
2035 
2036     case RISCV_IOMMU_REG_IOHPMCYCLES:
2037     case RISCV_IOMMU_REG_IOHPMCYCLES + 4:
2038         riscv_iommu_process_hpmcycle_write(s);
2039         break;
2040 
2041     case RISCV_IOMMU_REG_IOHPMEVT_BASE ...
2042         RISCV_IOMMU_REG_IOHPMEVT(RISCV_IOMMU_IOCOUNT_NUM) + 4:
2043         riscv_iommu_process_hpmevt_write(s, regb & ~7);
2044         break;
2045     }
2046 }
2047 
2048 /*
2049  * Write the resulting value of 'data' for the reg specified
2050  * by 'reg_addr', after considering read-only/read-write/write-clear
2051  * bits, in the pointer 'dest'.
2052  *
2053  * The result is written in little-endian.
2054  */
2055 static void riscv_iommu_write_reg_val(RISCVIOMMUState *s,
2056                                       void *dest, hwaddr reg_addr,
2057                                       int size, uint64_t data)
2058 {
2059     uint64_t ro = ldn_le_p(&s->regs_ro[reg_addr], size);
2060     uint64_t wc = ldn_le_p(&s->regs_wc[reg_addr], size);
2061     uint64_t rw = ldn_le_p(&s->regs_rw[reg_addr], size);
2062 
2063     stn_le_p(dest, size, ((rw & ro) | (data & ~ro)) & ~(data & wc));
2064 }
2065 
2066 static MemTxResult riscv_iommu_mmio_write(void *opaque, hwaddr addr,
2067                                           uint64_t data, unsigned size,
2068                                           MemTxAttrs attrs)
2069 {
2070     riscv_iommu_process_fn *process_fn = NULL;
2071     RISCVIOMMUState *s = opaque;
2072     uint32_t regb = addr & ~3;
2073     uint32_t busy = 0;
2074     uint64_t val = 0;
2075     bool cy_inh = false;
2076 
2077     if ((addr & (size - 1)) != 0) {
2078         /* Unsupported MMIO alignment or access size */
2079         return MEMTX_ERROR;
2080     }
2081 
2082     if (addr + size > RISCV_IOMMU_REG_MSI_CONFIG) {
2083         /* Unsupported MMIO access location. */
2084         return MEMTX_ACCESS_ERROR;
2085     }
2086 
2087     /* Track actionable MMIO write. */
2088     switch (regb) {
2089     case RISCV_IOMMU_REG_DDTP:
2090     case RISCV_IOMMU_REG_DDTP + 4:
2091         process_fn = riscv_iommu_process_ddtp;
2092         regb = RISCV_IOMMU_REG_DDTP;
2093         busy = RISCV_IOMMU_DDTP_BUSY;
2094         break;
2095 
2096     case RISCV_IOMMU_REG_CQT:
2097         process_fn = riscv_iommu_process_cq_tail;
2098         break;
2099 
2100     case RISCV_IOMMU_REG_CQCSR:
2101         process_fn = riscv_iommu_process_cq_control;
2102         busy = RISCV_IOMMU_CQCSR_BUSY;
2103         break;
2104 
2105     case RISCV_IOMMU_REG_FQCSR:
2106         process_fn = riscv_iommu_process_fq_control;
2107         busy = RISCV_IOMMU_FQCSR_BUSY;
2108         break;
2109 
2110     case RISCV_IOMMU_REG_PQCSR:
2111         process_fn = riscv_iommu_process_pq_control;
2112         busy = RISCV_IOMMU_PQCSR_BUSY;
2113         break;
2114 
2115     case RISCV_IOMMU_REG_ICVEC:
2116     case RISCV_IOMMU_REG_IPSR:
2117         /*
2118          * ICVEC and IPSR have special read/write procedures. We'll
2119          * call their respective helpers and exit.
2120          */
2121         riscv_iommu_write_reg_val(s, &val, addr, size, data);
2122 
2123         /*
2124          * 'val' is stored as LE. Switch to host endianess
2125          * before using it.
2126          */
2127         val = le64_to_cpu(val);
2128 
2129         if (regb == RISCV_IOMMU_REG_ICVEC) {
2130             riscv_iommu_update_icvec(s, val);
2131         } else {
2132             riscv_iommu_update_ipsr(s, val);
2133         }
2134 
2135         return MEMTX_OK;
2136 
2137     case RISCV_IOMMU_REG_TR_REQ_CTL:
2138         process_fn = riscv_iommu_process_dbg;
2139         regb = RISCV_IOMMU_REG_TR_REQ_CTL;
2140         busy = RISCV_IOMMU_TR_REQ_CTL_GO_BUSY;
2141         break;
2142 
2143     case RISCV_IOMMU_REG_IOCOUNTINH:
2144         if (addr != RISCV_IOMMU_REG_IOCOUNTINH) {
2145             break;
2146         }
2147         /* Store previous value of CY bit. */
2148         cy_inh = !!(riscv_iommu_reg_get32(s, RISCV_IOMMU_REG_IOCOUNTINH) &
2149             RISCV_IOMMU_IOCOUNTINH_CY);
2150         break;
2151 
2152 
2153     default:
2154         break;
2155     }
2156 
2157     /*
2158      * Registers update might be not synchronized with core logic.
2159      * If system software updates register when relevant BUSY bit
2160      * is set IOMMU behavior of additional writes to the register
2161      * is UNSPECIFIED.
2162      */
2163     riscv_iommu_write_reg_val(s, &s->regs_rw[addr], addr, size, data);
2164 
2165     /* Busy flag update, MSB 4-byte register. */
2166     if (busy) {
2167         uint32_t rw = ldl_le_p(&s->regs_rw[regb]);
2168         stl_le_p(&s->regs_rw[regb], rw | busy);
2169     }
2170 
2171     /* Process HPM writes and update any internal state if needed. */
2172     if (regb >= RISCV_IOMMU_REG_IOCOUNTOVF &&
2173         regb <= (RISCV_IOMMU_REG_IOHPMEVT(RISCV_IOMMU_IOCOUNT_NUM) + 4)) {
2174         riscv_iommu_process_hpm_writes(s, regb, cy_inh);
2175     }
2176 
2177     if (process_fn) {
2178         process_fn(s);
2179     }
2180 
2181     return MEMTX_OK;
2182 }
2183 
2184 static MemTxResult riscv_iommu_mmio_read(void *opaque, hwaddr addr,
2185     uint64_t *data, unsigned size, MemTxAttrs attrs)
2186 {
2187     RISCVIOMMUState *s = opaque;
2188     uint64_t val = -1;
2189     uint8_t *ptr;
2190 
2191     if ((addr & (size - 1)) != 0) {
2192         /* Unsupported MMIO alignment. */
2193         return MEMTX_ERROR;
2194     }
2195 
2196     if (addr + size > RISCV_IOMMU_REG_MSI_CONFIG) {
2197         return MEMTX_ACCESS_ERROR;
2198     }
2199 
2200     /* Compute cycle register value. */
2201     if ((addr & ~7) == RISCV_IOMMU_REG_IOHPMCYCLES) {
2202         val = riscv_iommu_hpmcycle_read(s);
2203         ptr = (uint8_t *)&val + (addr & 7);
2204     } else if ((addr & ~3) == RISCV_IOMMU_REG_IOCOUNTOVF) {
2205         /*
2206          * Software can read RISCV_IOMMU_REG_IOCOUNTOVF before timer
2207          * callback completes. In which case CY_OF bit in
2208          * RISCV_IOMMU_IOHPMCYCLES_OVF would be 0. Here we take the
2209          * CY_OF bit state from RISCV_IOMMU_REG_IOHPMCYCLES register as
2210          * it's not dependent over the timer callback and is computed
2211          * from cycle overflow.
2212          */
2213         val = ldq_le_p(&s->regs_rw[addr]);
2214         val |= (riscv_iommu_hpmcycle_read(s) & RISCV_IOMMU_IOHPMCYCLES_OVF)
2215                    ? RISCV_IOMMU_IOCOUNTOVF_CY
2216                    : 0;
2217         ptr = (uint8_t *)&val + (addr & 3);
2218     } else {
2219         ptr = &s->regs_rw[addr];
2220     }
2221 
2222     val = ldn_le_p(ptr, size);
2223 
2224     *data = val;
2225 
2226     return MEMTX_OK;
2227 }
2228 
2229 static const MemoryRegionOps riscv_iommu_mmio_ops = {
2230     .read_with_attrs = riscv_iommu_mmio_read,
2231     .write_with_attrs = riscv_iommu_mmio_write,
2232     .endianness = DEVICE_NATIVE_ENDIAN,
2233     .impl = {
2234         .min_access_size = 4,
2235         .max_access_size = 8,
2236         .unaligned = false,
2237     },
2238     .valid = {
2239         .min_access_size = 4,
2240         .max_access_size = 8,
2241     }
2242 };
2243 
2244 /*
2245  * Translations matching MSI pattern check are redirected to "riscv-iommu-trap"
2246  * memory region as untranslated address, for additional MSI/MRIF interception
2247  * by IOMMU interrupt remapping implementation.
2248  * Note: Device emulation code generating an MSI is expected to provide a valid
2249  * memory transaction attributes with requested_id set.
2250  */
2251 static MemTxResult riscv_iommu_trap_write(void *opaque, hwaddr addr,
2252     uint64_t data, unsigned size, MemTxAttrs attrs)
2253 {
2254     RISCVIOMMUState* s = (RISCVIOMMUState *)opaque;
2255     RISCVIOMMUContext *ctx;
2256     MemTxResult res;
2257     void *ref;
2258     uint32_t devid = attrs.requester_id;
2259 
2260     if (attrs.unspecified) {
2261         return MEMTX_ACCESS_ERROR;
2262     }
2263 
2264     /* FIXME: PCIe bus remapping for attached endpoints. */
2265     devid |= s->bus << 8;
2266 
2267     ctx = riscv_iommu_ctx(s, devid, 0, &ref);
2268     if (ctx == NULL) {
2269         res = MEMTX_ACCESS_ERROR;
2270     } else {
2271         res = riscv_iommu_msi_write(s, ctx, addr, data, size, attrs);
2272     }
2273     riscv_iommu_ctx_put(s, ref);
2274     return res;
2275 }
2276 
2277 static MemTxResult riscv_iommu_trap_read(void *opaque, hwaddr addr,
2278     uint64_t *data, unsigned size, MemTxAttrs attrs)
2279 {
2280     return MEMTX_ACCESS_ERROR;
2281 }
2282 
2283 static const MemoryRegionOps riscv_iommu_trap_ops = {
2284     .read_with_attrs = riscv_iommu_trap_read,
2285     .write_with_attrs = riscv_iommu_trap_write,
2286     .endianness = DEVICE_LITTLE_ENDIAN,
2287     .impl = {
2288         .min_access_size = 4,
2289         .max_access_size = 8,
2290         .unaligned = true,
2291     },
2292     .valid = {
2293         .min_access_size = 4,
2294         .max_access_size = 8,
2295     }
2296 };
2297 
2298 void riscv_iommu_set_cap_igs(RISCVIOMMUState *s, riscv_iommu_igs_mode mode)
2299 {
2300     s->cap = set_field(s->cap, RISCV_IOMMU_CAP_IGS, mode);
2301 }
2302 
2303 static void riscv_iommu_instance_init(Object *obj)
2304 {
2305     RISCVIOMMUState *s = RISCV_IOMMU(obj);
2306 
2307     /* Enable translation debug interface */
2308     s->cap = RISCV_IOMMU_CAP_DBG;
2309 
2310     /* Report QEMU target physical address space limits */
2311     s->cap = set_field(s->cap, RISCV_IOMMU_CAP_PAS,
2312                        TARGET_PHYS_ADDR_SPACE_BITS);
2313 
2314     /* TODO: method to report supported PID bits */
2315     s->pid_bits = 8; /* restricted to size of MemTxAttrs.pid */
2316     s->cap |= RISCV_IOMMU_CAP_PD8;
2317 
2318     /* register storage */
2319     s->regs_rw = g_new0(uint8_t, RISCV_IOMMU_REG_SIZE);
2320     s->regs_ro = g_new0(uint8_t, RISCV_IOMMU_REG_SIZE);
2321     s->regs_wc = g_new0(uint8_t, RISCV_IOMMU_REG_SIZE);
2322 
2323      /* Mark all registers read-only */
2324     memset(s->regs_ro, 0xff, RISCV_IOMMU_REG_SIZE);
2325 
2326     /* Device translation context cache */
2327     s->ctx_cache = g_hash_table_new_full(riscv_iommu_ctx_hash,
2328                                          riscv_iommu_ctx_equal,
2329                                          g_free, NULL);
2330 
2331     s->iot_cache = g_hash_table_new_full(riscv_iommu_iot_hash,
2332                                          riscv_iommu_iot_equal,
2333                                          g_free, NULL);
2334 
2335     s->iommus.le_next = NULL;
2336     s->iommus.le_prev = NULL;
2337     QLIST_INIT(&s->spaces);
2338 }
2339 
2340 static void riscv_iommu_realize(DeviceState *dev, Error **errp)
2341 {
2342     RISCVIOMMUState *s = RISCV_IOMMU(dev);
2343 
2344     s->cap |= s->version & RISCV_IOMMU_CAP_VERSION;
2345     if (s->enable_msi) {
2346         s->cap |= RISCV_IOMMU_CAP_MSI_FLAT | RISCV_IOMMU_CAP_MSI_MRIF;
2347     }
2348     if (s->enable_ats) {
2349         s->cap |= RISCV_IOMMU_CAP_ATS;
2350     }
2351     if (s->enable_s_stage) {
2352         s->cap |= RISCV_IOMMU_CAP_SV32 | RISCV_IOMMU_CAP_SV39 |
2353                   RISCV_IOMMU_CAP_SV48 | RISCV_IOMMU_CAP_SV57;
2354     }
2355     if (s->enable_g_stage) {
2356         s->cap |= RISCV_IOMMU_CAP_SV32X4 | RISCV_IOMMU_CAP_SV39X4 |
2357                   RISCV_IOMMU_CAP_SV48X4 | RISCV_IOMMU_CAP_SV57X4 |
2358                   RISCV_IOMMU_CAP_SVRSW60T59B;
2359     }
2360 
2361     if (s->hpm_cntrs > 0) {
2362         /* Clip number of HPM counters to maximum supported (31). */
2363         if (s->hpm_cntrs > RISCV_IOMMU_IOCOUNT_NUM) {
2364             s->hpm_cntrs = RISCV_IOMMU_IOCOUNT_NUM;
2365         }
2366         /* Enable hardware performance monitor interface */
2367         s->cap |= RISCV_IOMMU_CAP_HPM;
2368     }
2369 
2370     /* Out-of-reset translation mode: OFF (DMA disabled) BARE (passthrough) */
2371     s->ddtp = set_field(0, RISCV_IOMMU_DDTP_MODE, s->enable_off ?
2372                         RISCV_IOMMU_DDTP_MODE_OFF : RISCV_IOMMU_DDTP_MODE_BARE);
2373 
2374     /*
2375      * Register complete MMIO space, including MSI/PBA registers.
2376      * Note, PCIDevice implementation will add overlapping MR for MSI/PBA,
2377      * managed directly by the PCIDevice implementation.
2378      */
2379     memory_region_init_io(&s->regs_mr, OBJECT(dev), &riscv_iommu_mmio_ops, s,
2380         "riscv-iommu-regs", RISCV_IOMMU_REG_SIZE);
2381 
2382     /* Set power-on register state */
2383     stq_le_p(&s->regs_rw[RISCV_IOMMU_REG_CAP], s->cap);
2384     stq_le_p(&s->regs_rw[RISCV_IOMMU_REG_FCTL], 0);
2385     stq_le_p(&s->regs_ro[RISCV_IOMMU_REG_FCTL],
2386              ~(RISCV_IOMMU_FCTL_BE | RISCV_IOMMU_FCTL_WSI));
2387     stq_le_p(&s->regs_ro[RISCV_IOMMU_REG_DDTP],
2388         ~(RISCV_IOMMU_DDTP_PPN | RISCV_IOMMU_DDTP_MODE));
2389     stq_le_p(&s->regs_ro[RISCV_IOMMU_REG_CQB],
2390         ~(RISCV_IOMMU_CQB_LOG2SZ | RISCV_IOMMU_CQB_PPN));
2391     stq_le_p(&s->regs_ro[RISCV_IOMMU_REG_FQB],
2392         ~(RISCV_IOMMU_FQB_LOG2SZ | RISCV_IOMMU_FQB_PPN));
2393     stq_le_p(&s->regs_ro[RISCV_IOMMU_REG_PQB],
2394         ~(RISCV_IOMMU_PQB_LOG2SZ | RISCV_IOMMU_PQB_PPN));
2395     stl_le_p(&s->regs_wc[RISCV_IOMMU_REG_CQCSR], RISCV_IOMMU_CQCSR_CQMF |
2396         RISCV_IOMMU_CQCSR_CMD_TO | RISCV_IOMMU_CQCSR_CMD_ILL);
2397     stl_le_p(&s->regs_ro[RISCV_IOMMU_REG_CQCSR], RISCV_IOMMU_CQCSR_CQON |
2398         RISCV_IOMMU_CQCSR_BUSY);
2399     stl_le_p(&s->regs_wc[RISCV_IOMMU_REG_FQCSR], RISCV_IOMMU_FQCSR_FQMF |
2400         RISCV_IOMMU_FQCSR_FQOF);
2401     stl_le_p(&s->regs_ro[RISCV_IOMMU_REG_FQCSR], RISCV_IOMMU_FQCSR_FQON |
2402         RISCV_IOMMU_FQCSR_BUSY);
2403     stl_le_p(&s->regs_wc[RISCV_IOMMU_REG_PQCSR], RISCV_IOMMU_PQCSR_PQMF |
2404         RISCV_IOMMU_PQCSR_PQOF);
2405     stl_le_p(&s->regs_ro[RISCV_IOMMU_REG_PQCSR], RISCV_IOMMU_PQCSR_PQON |
2406         RISCV_IOMMU_PQCSR_BUSY);
2407     stl_le_p(&s->regs_wc[RISCV_IOMMU_REG_IPSR], ~0);
2408     stl_le_p(&s->regs_ro[RISCV_IOMMU_REG_ICVEC], 0);
2409     stq_le_p(&s->regs_rw[RISCV_IOMMU_REG_DDTP], s->ddtp);
2410     /* If debug registers enabled. */
2411     if (s->cap & RISCV_IOMMU_CAP_DBG) {
2412         stq_le_p(&s->regs_ro[RISCV_IOMMU_REG_TR_REQ_IOVA], 0);
2413         stq_le_p(&s->regs_ro[RISCV_IOMMU_REG_TR_REQ_CTL],
2414             RISCV_IOMMU_TR_REQ_CTL_GO_BUSY);
2415     }
2416 
2417     /* If HPM registers are enabled. */
2418     if (s->cap & RISCV_IOMMU_CAP_HPM) {
2419         /* +1 for cycle counter bit. */
2420         stl_le_p(&s->regs_ro[RISCV_IOMMU_REG_IOCOUNTINH],
2421                  ~((2 << s->hpm_cntrs) - 1));
2422         stq_le_p(&s->regs_ro[RISCV_IOMMU_REG_IOHPMCYCLES], 0);
2423         memset(&s->regs_ro[RISCV_IOMMU_REG_IOHPMCTR_BASE],
2424                0x00, s->hpm_cntrs * 8);
2425         memset(&s->regs_ro[RISCV_IOMMU_REG_IOHPMEVT_BASE],
2426                0x00, s->hpm_cntrs * 8);
2427     }
2428 
2429     /* Memory region for downstream access, if specified. */
2430     if (s->target_mr) {
2431         s->target_as = g_new0(AddressSpace, 1);
2432         address_space_init(s->target_as, s->target_mr,
2433             "riscv-iommu-downstream");
2434     } else {
2435         /* Fallback to global system memory. */
2436         s->target_as = &address_space_memory;
2437     }
2438 
2439     /* Memory region for untranslated MRIF/MSI writes */
2440     memory_region_init_io(&s->trap_mr, OBJECT(dev), &riscv_iommu_trap_ops, s,
2441             "riscv-iommu-trap", ~0ULL);
2442     address_space_init(&s->trap_as, &s->trap_mr, "riscv-iommu-trap-as");
2443 
2444     if (s->cap & RISCV_IOMMU_CAP_HPM) {
2445         s->hpm_timer =
2446             timer_new_ns(QEMU_CLOCK_VIRTUAL, riscv_iommu_hpm_timer_cb, s);
2447         s->hpm_event_ctr_map = g_hash_table_new(g_direct_hash, g_direct_equal);
2448     }
2449 }
2450 
2451 static void riscv_iommu_unrealize(DeviceState *dev)
2452 {
2453     RISCVIOMMUState *s = RISCV_IOMMU(dev);
2454 
2455     g_hash_table_unref(s->iot_cache);
2456     g_hash_table_unref(s->ctx_cache);
2457 
2458     if (s->cap & RISCV_IOMMU_CAP_HPM) {
2459         g_hash_table_unref(s->hpm_event_ctr_map);
2460         timer_free(s->hpm_timer);
2461     }
2462 }
2463 
2464 void riscv_iommu_reset(RISCVIOMMUState *s)
2465 {
2466     uint32_t reg_clr;
2467     int ddtp_mode;
2468 
2469     /*
2470      * Clear DDTP while setting DDTP_mode back to user
2471      * initial setting.
2472      */
2473     ddtp_mode = s->enable_off ?
2474                 RISCV_IOMMU_DDTP_MODE_OFF : RISCV_IOMMU_DDTP_MODE_BARE;
2475     s->ddtp = set_field(0, RISCV_IOMMU_DDTP_MODE, ddtp_mode);
2476     riscv_iommu_reg_set64(s, RISCV_IOMMU_REG_DDTP, s->ddtp);
2477 
2478     reg_clr = RISCV_IOMMU_CQCSR_CQEN | RISCV_IOMMU_CQCSR_CIE |
2479               RISCV_IOMMU_CQCSR_CQON | RISCV_IOMMU_CQCSR_BUSY;
2480     riscv_iommu_reg_mod32(s, RISCV_IOMMU_REG_CQCSR, 0, reg_clr);
2481 
2482     reg_clr = RISCV_IOMMU_FQCSR_FQEN | RISCV_IOMMU_FQCSR_FIE |
2483               RISCV_IOMMU_FQCSR_FQON | RISCV_IOMMU_FQCSR_BUSY;
2484     riscv_iommu_reg_mod32(s, RISCV_IOMMU_REG_FQCSR, 0, reg_clr);
2485 
2486     reg_clr = RISCV_IOMMU_PQCSR_PQEN | RISCV_IOMMU_PQCSR_PIE |
2487               RISCV_IOMMU_PQCSR_PQON | RISCV_IOMMU_PQCSR_BUSY;
2488     riscv_iommu_reg_mod32(s, RISCV_IOMMU_REG_PQCSR, 0, reg_clr);
2489 
2490     riscv_iommu_reg_mod64(s, RISCV_IOMMU_REG_TR_REQ_CTL, 0,
2491                           RISCV_IOMMU_TR_REQ_CTL_GO_BUSY);
2492 
2493     riscv_iommu_reg_set32(s, RISCV_IOMMU_REG_IPSR, 0);
2494 
2495     g_hash_table_remove_all(s->ctx_cache);
2496     g_hash_table_remove_all(s->iot_cache);
2497 }
2498 
2499 static const Property riscv_iommu_properties[] = {
2500     DEFINE_PROP_UINT32("version", RISCVIOMMUState, version,
2501         RISCV_IOMMU_SPEC_DOT_VER),
2502     DEFINE_PROP_UINT32("bus", RISCVIOMMUState, bus, 0x0),
2503     DEFINE_PROP_UINT32("ioatc-limit", RISCVIOMMUState, iot_limit,
2504         LIMIT_CACHE_IOT),
2505     DEFINE_PROP_BOOL("intremap", RISCVIOMMUState, enable_msi, TRUE),
2506     DEFINE_PROP_BOOL("ats", RISCVIOMMUState, enable_ats, TRUE),
2507     DEFINE_PROP_BOOL("off", RISCVIOMMUState, enable_off, TRUE),
2508     DEFINE_PROP_BOOL("s-stage", RISCVIOMMUState, enable_s_stage, TRUE),
2509     DEFINE_PROP_BOOL("g-stage", RISCVIOMMUState, enable_g_stage, TRUE),
2510     DEFINE_PROP_LINK("downstream-mr", RISCVIOMMUState, target_mr,
2511         TYPE_MEMORY_REGION, MemoryRegion *),
2512     DEFINE_PROP_UINT8("hpm-counters", RISCVIOMMUState, hpm_cntrs,
2513                       RISCV_IOMMU_IOCOUNT_NUM),
2514 };
2515 
2516 static void riscv_iommu_class_init(ObjectClass *klass, const void *data)
2517 {
2518     DeviceClass *dc = DEVICE_CLASS(klass);
2519 
2520     /* internal device for riscv-iommu-{pci/sys}, not user-creatable */
2521     dc->user_creatable = false;
2522     dc->realize = riscv_iommu_realize;
2523     dc->unrealize = riscv_iommu_unrealize;
2524     device_class_set_props(dc, riscv_iommu_properties);
2525 }
2526 
2527 static const TypeInfo riscv_iommu_info = {
2528     .name = TYPE_RISCV_IOMMU,
2529     .parent = TYPE_DEVICE,
2530     .instance_size = sizeof(RISCVIOMMUState),
2531     .instance_init = riscv_iommu_instance_init,
2532     .class_init = riscv_iommu_class_init,
2533 };
2534 
2535 static const char *IOMMU_FLAG_STR[] = {
2536     "NA",
2537     "RO",
2538     "WR",
2539     "RW",
2540 };
2541 
2542 /* RISC-V IOMMU Memory Region - Address Translation Space */
2543 static IOMMUTLBEntry riscv_iommu_memory_region_translate(
2544     IOMMUMemoryRegion *iommu_mr, hwaddr addr,
2545     IOMMUAccessFlags flag, int iommu_idx)
2546 {
2547     RISCVIOMMUSpace *as = container_of(iommu_mr, RISCVIOMMUSpace, iova_mr);
2548     RISCVIOMMUContext *ctx;
2549     void *ref;
2550     IOMMUTLBEntry iotlb = {
2551         .iova = addr,
2552         .target_as = as->iommu->target_as,
2553         .addr_mask = ~0ULL,
2554         .perm = flag,
2555     };
2556 
2557     ctx = riscv_iommu_ctx(as->iommu, as->devid, iommu_idx, &ref);
2558     if (ctx == NULL) {
2559         /* Translation disabled or invalid. */
2560         iotlb.addr_mask = 0;
2561         iotlb.perm = IOMMU_NONE;
2562     } else if (riscv_iommu_translate(as->iommu, ctx, &iotlb, true)) {
2563         /* Translation disabled or fault reported. */
2564         iotlb.addr_mask = 0;
2565         iotlb.perm = IOMMU_NONE;
2566     }
2567 
2568     /* Trace all dma translations with original access flags. */
2569     trace_riscv_iommu_dma(as->iommu->parent_obj.id, PCI_BUS_NUM(as->devid),
2570                           PCI_SLOT(as->devid), PCI_FUNC(as->devid), iommu_idx,
2571                           IOMMU_FLAG_STR[flag & IOMMU_RW], iotlb.iova,
2572                           iotlb.translated_addr);
2573 
2574     riscv_iommu_ctx_put(as->iommu, ref);
2575 
2576     return iotlb;
2577 }
2578 
2579 static int riscv_iommu_memory_region_notify(
2580     IOMMUMemoryRegion *iommu_mr, IOMMUNotifierFlag old,
2581     IOMMUNotifierFlag new, Error **errp)
2582 {
2583     RISCVIOMMUSpace *as = container_of(iommu_mr, RISCVIOMMUSpace, iova_mr);
2584 
2585     if (old == IOMMU_NOTIFIER_NONE) {
2586         as->notifier = true;
2587         trace_riscv_iommu_notifier_add(iommu_mr->parent_obj.name);
2588     } else if (new == IOMMU_NOTIFIER_NONE) {
2589         as->notifier = false;
2590         trace_riscv_iommu_notifier_del(iommu_mr->parent_obj.name);
2591     }
2592 
2593     return 0;
2594 }
2595 
2596 static inline bool pci_is_iommu(PCIDevice *pdev)
2597 {
2598     return pci_get_word(pdev->config + PCI_CLASS_DEVICE) == 0x0806;
2599 }
2600 
2601 static AddressSpace *riscv_iommu_find_as(PCIBus *bus, void *opaque, int devfn)
2602 {
2603     RISCVIOMMUState *s = (RISCVIOMMUState *) opaque;
2604     PCIDevice *pdev = pci_find_device(bus, pci_bus_num(bus), devfn);
2605     AddressSpace *as = NULL;
2606 
2607     if (pdev && pci_is_iommu(pdev)) {
2608         return s->target_as;
2609     }
2610 
2611     /* Find first registered IOMMU device */
2612     while (s->iommus.le_prev) {
2613         s = *(s->iommus.le_prev);
2614     }
2615 
2616     /* Find first matching IOMMU */
2617     while (s != NULL && as == NULL) {
2618         as = riscv_iommu_space(s, PCI_BUILD_BDF(pci_bus_num(bus), devfn));
2619         s = s->iommus.le_next;
2620     }
2621 
2622     return as ? as : &address_space_memory;
2623 }
2624 
2625 static const PCIIOMMUOps riscv_iommu_ops = {
2626     .get_address_space = riscv_iommu_find_as,
2627 };
2628 
2629 void riscv_iommu_pci_setup_iommu(RISCVIOMMUState *iommu, PCIBus *bus,
2630         Error **errp)
2631 {
2632     if (bus->iommu_ops &&
2633         bus->iommu_ops->get_address_space == riscv_iommu_find_as) {
2634         /* Allow multiple IOMMUs on the same PCIe bus, link known devices */
2635         RISCVIOMMUState *last = (RISCVIOMMUState *)bus->iommu_opaque;
2636         QLIST_INSERT_AFTER(last, iommu, iommus);
2637     } else if (!bus->iommu_ops && !bus->iommu_opaque) {
2638         pci_setup_iommu(bus, &riscv_iommu_ops, iommu);
2639     } else {
2640         error_setg(errp, "can't register secondary IOMMU for PCI bus #%d",
2641             pci_bus_num(bus));
2642     }
2643 }
2644 
2645 static int riscv_iommu_memory_region_index(IOMMUMemoryRegion *iommu_mr,
2646     MemTxAttrs attrs)
2647 {
2648     return attrs.unspecified ? RISCV_IOMMU_NOPROCID : (int)attrs.pid;
2649 }
2650 
2651 static int riscv_iommu_memory_region_index_len(IOMMUMemoryRegion *iommu_mr)
2652 {
2653     RISCVIOMMUSpace *as = container_of(iommu_mr, RISCVIOMMUSpace, iova_mr);
2654     return 1 << as->iommu->pid_bits;
2655 }
2656 
2657 static void riscv_iommu_memory_region_init(ObjectClass *klass, const void *data)
2658 {
2659     IOMMUMemoryRegionClass *imrc = IOMMU_MEMORY_REGION_CLASS(klass);
2660 
2661     imrc->translate = riscv_iommu_memory_region_translate;
2662     imrc->notify_flag_changed = riscv_iommu_memory_region_notify;
2663     imrc->attrs_to_index = riscv_iommu_memory_region_index;
2664     imrc->num_indexes = riscv_iommu_memory_region_index_len;
2665 }
2666 
2667 static const TypeInfo riscv_iommu_memory_region_info = {
2668     .parent = TYPE_IOMMU_MEMORY_REGION,
2669     .name = TYPE_RISCV_IOMMU_MEMORY_REGION,
2670     .class_init = riscv_iommu_memory_region_init,
2671 };
2672 
2673 static void riscv_iommu_register_mr_types(void)
2674 {
2675     type_register_static(&riscv_iommu_memory_region_info);
2676     type_register_static(&riscv_iommu_info);
2677 }
2678 
2679 type_init(riscv_iommu_register_mr_types);
2680