xref: /openbmc/qemu/hw/s390x/s390-pci-inst.c (revision ef536007)
1 /*
2  * s390 PCI instructions
3  *
4  * Copyright 2014 IBM Corp.
5  * Author(s): Frank Blaschka <frank.blaschka@de.ibm.com>
6  *            Hong Bo Li <lihbbj@cn.ibm.com>
7  *            Yi Min Zhao <zyimin@cn.ibm.com>
8  *
9  * This work is licensed under the terms of the GNU GPL, version 2 or (at
10  * your option) any later version. See the COPYING file in the top-level
11  * directory.
12  */
13 
14 #include "qemu/osdep.h"
15 #include "exec/memop.h"
16 #include "exec/memory-internal.h"
17 #include "qemu/error-report.h"
18 #include "sysemu/hw_accel.h"
19 #include "hw/s390x/s390-pci-inst.h"
20 #include "hw/s390x/s390-pci-bus.h"
21 #include "hw/s390x/s390-pci-kvm.h"
22 #include "hw/s390x/s390-pci-vfio.h"
23 #include "hw/s390x/tod.h"
24 
25 #ifndef DEBUG_S390PCI_INST
26 #define DEBUG_S390PCI_INST  0
27 #endif
28 
29 #define DPRINTF(fmt, ...)                                          \
30     do {                                                           \
31         if (DEBUG_S390PCI_INST) {                                  \
32             fprintf(stderr, "s390pci-inst: " fmt, ## __VA_ARGS__); \
33         }                                                          \
34     } while (0)
35 
36 static inline void inc_dma_avail(S390PCIIOMMU *iommu)
37 {
38     if (iommu->dma_limit) {
39         iommu->dma_limit->avail++;
40     }
41 }
42 
43 static inline void dec_dma_avail(S390PCIIOMMU *iommu)
44 {
45     if (iommu->dma_limit) {
46         iommu->dma_limit->avail--;
47     }
48 }
49 
50 static void s390_set_status_code(CPUS390XState *env,
51                                  uint8_t r, uint64_t status_code)
52 {
53     env->regs[r] &= ~0xff000000ULL;
54     env->regs[r] |= (status_code & 0xff) << 24;
55 }
56 
57 static int list_pci(ClpReqRspListPci *rrb, uint8_t *cc)
58 {
59     S390PCIBusDevice *pbdev = NULL;
60     S390pciState *s = s390_get_phb();
61     uint32_t res_code, initial_l2, g_l2;
62     int rc, i;
63     uint64_t resume_token;
64 
65     rc = 0;
66     if (lduw_p(&rrb->request.hdr.len) != 32) {
67         res_code = CLP_RC_LEN;
68         rc = -EINVAL;
69         goto out;
70     }
71 
72     if ((ldl_p(&rrb->request.fmt) & CLP_MASK_FMT) != 0) {
73         res_code = CLP_RC_FMT;
74         rc = -EINVAL;
75         goto out;
76     }
77 
78     if ((ldl_p(&rrb->request.fmt) & ~CLP_MASK_FMT) != 0 ||
79         ldq_p(&rrb->request.reserved1) != 0) {
80         res_code = CLP_RC_RESNOT0;
81         rc = -EINVAL;
82         goto out;
83     }
84 
85     resume_token = ldq_p(&rrb->request.resume_token);
86 
87     if (resume_token) {
88         pbdev = s390_pci_find_dev_by_idx(s, resume_token);
89         if (!pbdev) {
90             res_code = CLP_RC_LISTPCI_BADRT;
91             rc = -EINVAL;
92             goto out;
93         }
94     } else {
95         pbdev = s390_pci_find_next_avail_dev(s, NULL);
96     }
97 
98     if (lduw_p(&rrb->response.hdr.len) < 48) {
99         res_code = CLP_RC_8K;
100         rc = -EINVAL;
101         goto out;
102     }
103 
104     initial_l2 = lduw_p(&rrb->response.hdr.len);
105     if ((initial_l2 - LIST_PCI_HDR_LEN) % sizeof(ClpFhListEntry)
106         != 0) {
107         res_code = CLP_RC_LEN;
108         rc = -EINVAL;
109         *cc = 3;
110         goto out;
111     }
112 
113     stl_p(&rrb->response.fmt, 0);
114     stq_p(&rrb->response.reserved1, 0);
115     stl_p(&rrb->response.mdd, FH_MASK_SHM);
116     stw_p(&rrb->response.max_fn, PCI_MAX_FUNCTIONS);
117     rrb->response.flags = UID_CHECKING_ENABLED;
118     rrb->response.entry_size = sizeof(ClpFhListEntry);
119 
120     i = 0;
121     g_l2 = LIST_PCI_HDR_LEN;
122     while (g_l2 < initial_l2 && pbdev) {
123         stw_p(&rrb->response.fh_list[i].device_id,
124             pci_get_word(pbdev->pdev->config + PCI_DEVICE_ID));
125         stw_p(&rrb->response.fh_list[i].vendor_id,
126             pci_get_word(pbdev->pdev->config + PCI_VENDOR_ID));
127         /* Ignore RESERVED devices. */
128         stl_p(&rrb->response.fh_list[i].config,
129             pbdev->state == ZPCI_FS_STANDBY ? 0 : 1 << 31);
130         stl_p(&rrb->response.fh_list[i].fid, pbdev->fid);
131         stl_p(&rrb->response.fh_list[i].fh, pbdev->fh);
132 
133         g_l2 += sizeof(ClpFhListEntry);
134         /* Add endian check for DPRINTF? */
135         DPRINTF("g_l2 %d vendor id 0x%x device id 0x%x fid 0x%x fh 0x%x\n",
136                 g_l2,
137                 lduw_p(&rrb->response.fh_list[i].vendor_id),
138                 lduw_p(&rrb->response.fh_list[i].device_id),
139                 ldl_p(&rrb->response.fh_list[i].fid),
140                 ldl_p(&rrb->response.fh_list[i].fh));
141         pbdev = s390_pci_find_next_avail_dev(s, pbdev);
142         i++;
143     }
144 
145     if (!pbdev) {
146         resume_token = 0;
147     } else {
148         resume_token = pbdev->fh & FH_MASK_INDEX;
149     }
150     stq_p(&rrb->response.resume_token, resume_token);
151     stw_p(&rrb->response.hdr.len, g_l2);
152     stw_p(&rrb->response.hdr.rsp, CLP_RC_OK);
153 out:
154     if (rc) {
155         DPRINTF("list pci failed rc 0x%x\n", rc);
156         stw_p(&rrb->response.hdr.rsp, res_code);
157     }
158     return rc;
159 }
160 
161 int clp_service_call(S390CPU *cpu, uint8_t r2, uintptr_t ra)
162 {
163     ClpReqHdr *reqh;
164     ClpRspHdr *resh;
165     S390PCIBusDevice *pbdev;
166     uint32_t req_len;
167     uint32_t res_len;
168     uint8_t buffer[4096 * 2];
169     uint8_t cc = 0;
170     CPUS390XState *env = &cpu->env;
171     S390pciState *s = s390_get_phb();
172     int i;
173 
174     if (env->psw.mask & PSW_MASK_PSTATE) {
175         s390_program_interrupt(env, PGM_PRIVILEGED, ra);
176         return 0;
177     }
178 
179     if (s390_cpu_virt_mem_read(cpu, env->regs[r2], r2, buffer, sizeof(*reqh))) {
180         s390_cpu_virt_mem_handle_exc(cpu, ra);
181         return 0;
182     }
183     reqh = (ClpReqHdr *)buffer;
184     req_len = lduw_p(&reqh->len);
185     if (req_len < 16 || req_len > 8184 || (req_len % 8 != 0)) {
186         s390_program_interrupt(env, PGM_OPERAND, ra);
187         return 0;
188     }
189 
190     if (s390_cpu_virt_mem_read(cpu, env->regs[r2], r2, buffer,
191                                req_len + sizeof(*resh))) {
192         s390_cpu_virt_mem_handle_exc(cpu, ra);
193         return 0;
194     }
195     resh = (ClpRspHdr *)(buffer + req_len);
196     res_len = lduw_p(&resh->len);
197     if (res_len < 8 || res_len > 8176 || (res_len % 8 != 0)) {
198         s390_program_interrupt(env, PGM_OPERAND, ra);
199         return 0;
200     }
201     if ((req_len + res_len) > 8192) {
202         s390_program_interrupt(env, PGM_OPERAND, ra);
203         return 0;
204     }
205 
206     if (s390_cpu_virt_mem_read(cpu, env->regs[r2], r2, buffer,
207                                req_len + res_len)) {
208         s390_cpu_virt_mem_handle_exc(cpu, ra);
209         return 0;
210     }
211 
212     if (req_len != 32) {
213         stw_p(&resh->rsp, CLP_RC_LEN);
214         goto out;
215     }
216 
217     switch (lduw_p(&reqh->cmd)) {
218     case CLP_LIST_PCI: {
219         ClpReqRspListPci *rrb = (ClpReqRspListPci *)buffer;
220         list_pci(rrb, &cc);
221         break;
222     }
223     case CLP_SET_PCI_FN: {
224         ClpReqSetPci *reqsetpci = (ClpReqSetPci *)reqh;
225         ClpRspSetPci *ressetpci = (ClpRspSetPci *)resh;
226 
227         pbdev = s390_pci_find_dev_by_fh(s, ldl_p(&reqsetpci->fh));
228         if (!pbdev) {
229                 stw_p(&ressetpci->hdr.rsp, CLP_RC_SETPCIFN_FH);
230                 goto out;
231         }
232 
233         switch (reqsetpci->oc) {
234         case CLP_SET_ENABLE_PCI_FN:
235             switch (reqsetpci->ndas) {
236             case 0:
237                 stw_p(&ressetpci->hdr.rsp, CLP_RC_SETPCIFN_DMAAS);
238                 goto out;
239             case 1:
240                 break;
241             default:
242                 stw_p(&ressetpci->hdr.rsp, CLP_RC_SETPCIFN_RES);
243                 goto out;
244             }
245 
246             if (pbdev->fh & FH_MASK_ENABLE) {
247                 stw_p(&ressetpci->hdr.rsp, CLP_RC_SETPCIFN_FHOP);
248                 goto out;
249             }
250 
251             /*
252              * Take this opportunity to make sure we still have an accurate
253              * host fh.  It's possible part of the handle changed while the
254              * device was disabled to the guest (e.g. vfio hot reset for
255              * ISM during plug)
256              */
257             if (pbdev->interp) {
258                 /* Take this opportunity to make sure we are sync'd with host */
259                 if (!s390_pci_get_host_fh(pbdev, &pbdev->fh) ||
260                     !(pbdev->fh & FH_MASK_ENABLE)) {
261                     stw_p(&ressetpci->hdr.rsp, CLP_RC_SETPCIFN_FH);
262                     goto out;
263                 }
264             }
265             pbdev->fh |= FH_MASK_ENABLE;
266             pbdev->state = ZPCI_FS_ENABLED;
267             stl_p(&ressetpci->fh, pbdev->fh);
268             stw_p(&ressetpci->hdr.rsp, CLP_RC_OK);
269             break;
270         case CLP_SET_DISABLE_PCI_FN:
271             if (!(pbdev->fh & FH_MASK_ENABLE)) {
272                 stw_p(&ressetpci->hdr.rsp, CLP_RC_SETPCIFN_FHOP);
273                 goto out;
274             }
275             device_legacy_reset(DEVICE(pbdev));
276             pbdev->fh &= ~FH_MASK_ENABLE;
277             pbdev->state = ZPCI_FS_DISABLED;
278             stl_p(&ressetpci->fh, pbdev->fh);
279             stw_p(&ressetpci->hdr.rsp, CLP_RC_OK);
280             break;
281         default:
282             DPRINTF("unknown set pci command\n");
283             stw_p(&ressetpci->hdr.rsp, CLP_RC_SETPCIFN_FHOP);
284             break;
285         }
286         break;
287     }
288     case CLP_QUERY_PCI_FN: {
289         ClpReqQueryPci *reqquery = (ClpReqQueryPci *)reqh;
290         ClpRspQueryPci *resquery = (ClpRspQueryPci *)resh;
291 
292         pbdev = s390_pci_find_dev_by_fh(s, ldl_p(&reqquery->fh));
293         if (!pbdev) {
294             DPRINTF("query pci no pci dev\n");
295             stw_p(&resquery->hdr.rsp, CLP_RC_SETPCIFN_FH);
296             goto out;
297         }
298 
299         stq_p(&resquery->sdma, pbdev->zpci_fn.sdma);
300         stq_p(&resquery->edma, pbdev->zpci_fn.edma);
301         stw_p(&resquery->pchid, pbdev->zpci_fn.pchid);
302         stw_p(&resquery->vfn, pbdev->zpci_fn.vfn);
303         resquery->flags = pbdev->zpci_fn.flags;
304         resquery->pfgid = pbdev->zpci_fn.pfgid;
305         resquery->pft = pbdev->zpci_fn.pft;
306         resquery->fmbl = pbdev->zpci_fn.fmbl;
307         stl_p(&resquery->fid, pbdev->zpci_fn.fid);
308         stl_p(&resquery->uid, pbdev->zpci_fn.uid);
309         memcpy(resquery->pfip, pbdev->zpci_fn.pfip, CLP_PFIP_NR_SEGMENTS);
310         memcpy(resquery->util_str, pbdev->zpci_fn.util_str, CLP_UTIL_STR_LEN);
311 
312         for (i = 0; i < PCI_BAR_COUNT; i++) {
313             uint32_t data = pci_get_long(pbdev->pdev->config +
314                 PCI_BASE_ADDRESS_0 + (i * 4));
315 
316             stl_p(&resquery->bar[i], data);
317             resquery->bar_size[i] = pbdev->pdev->io_regions[i].size ?
318                                     ctz64(pbdev->pdev->io_regions[i].size) : 0;
319             DPRINTF("bar %d addr 0x%x size 0x%" PRIx64 "barsize 0x%x\n", i,
320                     ldl_p(&resquery->bar[i]),
321                     pbdev->pdev->io_regions[i].size,
322                     resquery->bar_size[i]);
323         }
324 
325         stw_p(&resquery->hdr.rsp, CLP_RC_OK);
326         break;
327     }
328     case CLP_QUERY_PCI_FNGRP: {
329         ClpRspQueryPciGrp *resgrp = (ClpRspQueryPciGrp *)resh;
330 
331         ClpReqQueryPciGrp *reqgrp = (ClpReqQueryPciGrp *)reqh;
332         S390PCIGroup *group;
333 
334         group = s390_group_find(reqgrp->g);
335         if (!group) {
336             /* We do not allow access to unknown groups */
337             /* The group must have been obtained with a vfio device */
338             stw_p(&resgrp->hdr.rsp, CLP_RC_QUERYPCIFG_PFGID);
339             goto out;
340         }
341         resgrp->fr = group->zpci_group.fr;
342         stq_p(&resgrp->dasm, group->zpci_group.dasm);
343         stq_p(&resgrp->msia, group->zpci_group.msia);
344         stw_p(&resgrp->mui, group->zpci_group.mui);
345         stw_p(&resgrp->i, group->zpci_group.i);
346         stw_p(&resgrp->maxstbl, group->zpci_group.maxstbl);
347         resgrp->version = group->zpci_group.version;
348         resgrp->dtsm = group->zpci_group.dtsm;
349         stw_p(&resgrp->hdr.rsp, CLP_RC_OK);
350         break;
351     }
352     default:
353         DPRINTF("unknown clp command\n");
354         stw_p(&resh->rsp, CLP_RC_CMD);
355         break;
356     }
357 
358 out:
359     if (s390_cpu_virt_mem_write(cpu, env->regs[r2], r2, buffer,
360                                 req_len + res_len)) {
361         s390_cpu_virt_mem_handle_exc(cpu, ra);
362         return 0;
363     }
364     setcc(cpu, cc);
365     return 0;
366 }
367 
368 /**
369  * Swap data contained in s390x big endian registers to little endian
370  * PCI bars.
371  *
372  * @ptr: a pointer to a uint64_t data field
373  * @len: the length of the valid data, must be 1,2,4 or 8
374  */
375 static int zpci_endian_swap(uint64_t *ptr, uint8_t len)
376 {
377     uint64_t data = *ptr;
378 
379     switch (len) {
380     case 1:
381         break;
382     case 2:
383         data = bswap16(data);
384         break;
385     case 4:
386         data = bswap32(data);
387         break;
388     case 8:
389         data = bswap64(data);
390         break;
391     default:
392         return -EINVAL;
393     }
394     *ptr = data;
395     return 0;
396 }
397 
398 static MemoryRegion *s390_get_subregion(MemoryRegion *mr, uint64_t offset,
399                                         uint8_t len)
400 {
401     MemoryRegion *subregion;
402     uint64_t subregion_size;
403 
404     QTAILQ_FOREACH(subregion, &mr->subregions, subregions_link) {
405         subregion_size = int128_get64(subregion->size);
406         if ((offset >= subregion->addr) &&
407             (offset + len) <= (subregion->addr + subregion_size)) {
408             mr = subregion;
409             break;
410         }
411     }
412     return mr;
413 }
414 
415 static MemTxResult zpci_read_bar(S390PCIBusDevice *pbdev, uint8_t pcias,
416                                  uint64_t offset, uint64_t *data, uint8_t len)
417 {
418     MemoryRegion *mr;
419 
420     mr = pbdev->pdev->io_regions[pcias].memory;
421     mr = s390_get_subregion(mr, offset, len);
422     offset -= mr->addr;
423     return memory_region_dispatch_read(mr, offset, data,
424                                        size_memop(len) | MO_BE,
425                                        MEMTXATTRS_UNSPECIFIED);
426 }
427 
428 int pcilg_service_call(S390CPU *cpu, uint8_t r1, uint8_t r2, uintptr_t ra)
429 {
430     CPUS390XState *env = &cpu->env;
431     S390PCIBusDevice *pbdev;
432     uint64_t offset;
433     uint64_t data;
434     MemTxResult result;
435     uint8_t len;
436     uint32_t fh;
437     uint8_t pcias;
438 
439     if (env->psw.mask & PSW_MASK_PSTATE) {
440         s390_program_interrupt(env, PGM_PRIVILEGED, ra);
441         return 0;
442     }
443 
444     if (r2 & 0x1) {
445         s390_program_interrupt(env, PGM_SPECIFICATION, ra);
446         return 0;
447     }
448 
449     fh = env->regs[r2] >> 32;
450     pcias = (env->regs[r2] >> 16) & 0xf;
451     len = env->regs[r2] & 0xf;
452     offset = env->regs[r2 + 1];
453 
454     if (!(fh & FH_MASK_ENABLE)) {
455         setcc(cpu, ZPCI_PCI_LS_INVAL_HANDLE);
456         return 0;
457     }
458 
459     pbdev = s390_pci_find_dev_by_fh(s390_get_phb(), fh);
460     if (!pbdev) {
461         DPRINTF("pcilg no pci dev\n");
462         setcc(cpu, ZPCI_PCI_LS_INVAL_HANDLE);
463         return 0;
464     }
465 
466     switch (pbdev->state) {
467     case ZPCI_FS_PERMANENT_ERROR:
468     case ZPCI_FS_ERROR:
469         setcc(cpu, ZPCI_PCI_LS_ERR);
470         s390_set_status_code(env, r2, ZPCI_PCI_ST_BLOCKED);
471         return 0;
472     default:
473         break;
474     }
475 
476     switch (pcias) {
477     case ZPCI_IO_BAR_MIN...ZPCI_IO_BAR_MAX:
478         if (!len || (len > (8 - (offset & 0x7)))) {
479             s390_program_interrupt(env, PGM_OPERAND, ra);
480             return 0;
481         }
482         result = zpci_read_bar(pbdev, pcias, offset, &data, len);
483         if (result != MEMTX_OK) {
484             s390_program_interrupt(env, PGM_OPERAND, ra);
485             return 0;
486         }
487         break;
488     case ZPCI_CONFIG_BAR:
489         if (!len || (len > (4 - (offset & 0x3))) || len == 3) {
490             s390_program_interrupt(env, PGM_OPERAND, ra);
491             return 0;
492         }
493         data =  pci_host_config_read_common(
494                    pbdev->pdev, offset, pci_config_size(pbdev->pdev), len);
495 
496         if (zpci_endian_swap(&data, len)) {
497             s390_program_interrupt(env, PGM_OPERAND, ra);
498             return 0;
499         }
500         break;
501     default:
502         DPRINTF("pcilg invalid space\n");
503         setcc(cpu, ZPCI_PCI_LS_ERR);
504         s390_set_status_code(env, r2, ZPCI_PCI_ST_INVAL_AS);
505         return 0;
506     }
507 
508     pbdev->fmb.counter[ZPCI_FMB_CNT_LD]++;
509 
510     env->regs[r1] = data;
511     setcc(cpu, ZPCI_PCI_LS_OK);
512     return 0;
513 }
514 
515 static MemTxResult zpci_write_bar(S390PCIBusDevice *pbdev, uint8_t pcias,
516                                   uint64_t offset, uint64_t data, uint8_t len)
517 {
518     MemoryRegion *mr;
519 
520     mr = pbdev->pdev->io_regions[pcias].memory;
521     mr = s390_get_subregion(mr, offset, len);
522     offset -= mr->addr;
523     return memory_region_dispatch_write(mr, offset, data,
524                                         size_memop(len) | MO_BE,
525                                         MEMTXATTRS_UNSPECIFIED);
526 }
527 
528 int pcistg_service_call(S390CPU *cpu, uint8_t r1, uint8_t r2, uintptr_t ra)
529 {
530     CPUS390XState *env = &cpu->env;
531     uint64_t offset, data;
532     S390PCIBusDevice *pbdev;
533     MemTxResult result;
534     uint8_t len;
535     uint32_t fh;
536     uint8_t pcias;
537 
538     if (env->psw.mask & PSW_MASK_PSTATE) {
539         s390_program_interrupt(env, PGM_PRIVILEGED, ra);
540         return 0;
541     }
542 
543     if (r2 & 0x1) {
544         s390_program_interrupt(env, PGM_SPECIFICATION, ra);
545         return 0;
546     }
547 
548     fh = env->regs[r2] >> 32;
549     pcias = (env->regs[r2] >> 16) & 0xf;
550     len = env->regs[r2] & 0xf;
551     offset = env->regs[r2 + 1];
552     data = env->regs[r1];
553 
554     if (!(fh & FH_MASK_ENABLE)) {
555         setcc(cpu, ZPCI_PCI_LS_INVAL_HANDLE);
556         return 0;
557     }
558 
559     pbdev = s390_pci_find_dev_by_fh(s390_get_phb(), fh);
560     if (!pbdev) {
561         DPRINTF("pcistg no pci dev\n");
562         setcc(cpu, ZPCI_PCI_LS_INVAL_HANDLE);
563         return 0;
564     }
565 
566     switch (pbdev->state) {
567     /* ZPCI_FS_RESERVED, ZPCI_FS_STANDBY and ZPCI_FS_DISABLED
568      * are already covered by the FH_MASK_ENABLE check above
569      */
570     case ZPCI_FS_PERMANENT_ERROR:
571     case ZPCI_FS_ERROR:
572         setcc(cpu, ZPCI_PCI_LS_ERR);
573         s390_set_status_code(env, r2, ZPCI_PCI_ST_BLOCKED);
574         return 0;
575     default:
576         break;
577     }
578 
579     switch (pcias) {
580         /* A ZPCI PCI card may use any BAR from BAR 0 to BAR 5 */
581     case ZPCI_IO_BAR_MIN...ZPCI_IO_BAR_MAX:
582         /* Check length:
583          * A length of 0 is invalid and length should not cross a double word
584          */
585         if (!len || (len > (8 - (offset & 0x7)))) {
586             s390_program_interrupt(env, PGM_OPERAND, ra);
587             return 0;
588         }
589 
590         result = zpci_write_bar(pbdev, pcias, offset, data, len);
591         if (result != MEMTX_OK) {
592             s390_program_interrupt(env, PGM_OPERAND, ra);
593             return 0;
594         }
595         break;
596     case ZPCI_CONFIG_BAR:
597         /* ZPCI uses the pseudo BAR number 15 as configuration space */
598         /* possible access lengths are 1,2,4 and must not cross a word */
599         if (!len || (len > (4 - (offset & 0x3))) || len == 3) {
600             s390_program_interrupt(env, PGM_OPERAND, ra);
601             return 0;
602         }
603         /* len = 1,2,4 so we do not need to test */
604         zpci_endian_swap(&data, len);
605         pci_host_config_write_common(pbdev->pdev, offset,
606                                      pci_config_size(pbdev->pdev),
607                                      data, len);
608         break;
609     default:
610         DPRINTF("pcistg invalid space\n");
611         setcc(cpu, ZPCI_PCI_LS_ERR);
612         s390_set_status_code(env, r2, ZPCI_PCI_ST_INVAL_AS);
613         return 0;
614     }
615 
616     pbdev->fmb.counter[ZPCI_FMB_CNT_ST]++;
617 
618     setcc(cpu, ZPCI_PCI_LS_OK);
619     return 0;
620 }
621 
622 static uint32_t s390_pci_update_iotlb(S390PCIIOMMU *iommu,
623                                       S390IOTLBEntry *entry)
624 {
625     S390IOTLBEntry *cache = g_hash_table_lookup(iommu->iotlb, &entry->iova);
626     IOMMUTLBEvent event = {
627         .type = entry->perm ? IOMMU_NOTIFIER_MAP : IOMMU_NOTIFIER_UNMAP,
628         .entry = {
629             .target_as = &address_space_memory,
630             .iova = entry->iova,
631             .translated_addr = entry->translated_addr,
632             .perm = entry->perm,
633             .addr_mask = ~TARGET_PAGE_MASK,
634         },
635     };
636 
637     if (event.type == IOMMU_NOTIFIER_UNMAP) {
638         if (!cache) {
639             goto out;
640         }
641         g_hash_table_remove(iommu->iotlb, &entry->iova);
642         inc_dma_avail(iommu);
643         /* Don't notify the iommu yet, maybe we can bundle contiguous unmaps */
644         goto out;
645     } else {
646         if (cache) {
647             if (cache->perm == entry->perm &&
648                 cache->translated_addr == entry->translated_addr) {
649                 goto out;
650             }
651 
652             event.type = IOMMU_NOTIFIER_UNMAP;
653             event.entry.perm = IOMMU_NONE;
654             memory_region_notify_iommu(&iommu->iommu_mr, 0, event);
655             event.type = IOMMU_NOTIFIER_MAP;
656             event.entry.perm = entry->perm;
657         }
658 
659         cache = g_new(S390IOTLBEntry, 1);
660         cache->iova = entry->iova;
661         cache->translated_addr = entry->translated_addr;
662         cache->len = TARGET_PAGE_SIZE;
663         cache->perm = entry->perm;
664         g_hash_table_replace(iommu->iotlb, &cache->iova, cache);
665         dec_dma_avail(iommu);
666     }
667 
668     /*
669      * All associated iotlb entries have already been cleared, trigger the
670      * unmaps.
671      */
672     memory_region_notify_iommu(&iommu->iommu_mr, 0, event);
673 
674 out:
675     return iommu->dma_limit ? iommu->dma_limit->avail : 1;
676 }
677 
678 static void s390_pci_batch_unmap(S390PCIIOMMU *iommu, uint64_t iova,
679                                  uint64_t len)
680 {
681     uint64_t remain = len, start = iova, end = start + len - 1, mask, size;
682     IOMMUTLBEvent event = {
683         .type = IOMMU_NOTIFIER_UNMAP,
684         .entry = {
685             .target_as = &address_space_memory,
686             .translated_addr = 0,
687             .perm = IOMMU_NONE,
688         },
689     };
690 
691     while (remain >= TARGET_PAGE_SIZE) {
692         mask = dma_aligned_pow2_mask(start, end, 64);
693         size = mask + 1;
694         event.entry.iova = start;
695         event.entry.addr_mask = mask;
696         memory_region_notify_iommu(&iommu->iommu_mr, 0, event);
697         start += size;
698         remain -= size;
699     }
700 }
701 
702 int rpcit_service_call(S390CPU *cpu, uint8_t r1, uint8_t r2, uintptr_t ra)
703 {
704     CPUS390XState *env = &cpu->env;
705     uint64_t iova, coalesce = 0;
706     uint32_t fh;
707     uint16_t error = 0;
708     S390PCIBusDevice *pbdev;
709     S390PCIIOMMU *iommu;
710     S390IOTLBEntry entry;
711     hwaddr start, end, sstart;
712     uint32_t dma_avail;
713     bool again;
714 
715     if (env->psw.mask & PSW_MASK_PSTATE) {
716         s390_program_interrupt(env, PGM_PRIVILEGED, ra);
717         return 0;
718     }
719 
720     if (r2 & 0x1) {
721         s390_program_interrupt(env, PGM_SPECIFICATION, ra);
722         return 0;
723     }
724 
725     fh = env->regs[r1] >> 32;
726     sstart = start = env->regs[r2];
727     end = start + env->regs[r2 + 1];
728 
729     pbdev = s390_pci_find_dev_by_fh(s390_get_phb(), fh);
730     if (!pbdev) {
731         DPRINTF("rpcit no pci dev\n");
732         setcc(cpu, ZPCI_PCI_LS_INVAL_HANDLE);
733         return 0;
734     }
735 
736     switch (pbdev->state) {
737     case ZPCI_FS_RESERVED:
738     case ZPCI_FS_STANDBY:
739     case ZPCI_FS_DISABLED:
740     case ZPCI_FS_PERMANENT_ERROR:
741         setcc(cpu, ZPCI_PCI_LS_INVAL_HANDLE);
742         return 0;
743     case ZPCI_FS_ERROR:
744         setcc(cpu, ZPCI_PCI_LS_ERR);
745         s390_set_status_code(env, r1, ZPCI_MOD_ST_ERROR_RECOVER);
746         return 0;
747     default:
748         break;
749     }
750 
751     iommu = pbdev->iommu;
752     if (iommu->dma_limit) {
753         dma_avail = iommu->dma_limit->avail;
754     } else {
755         dma_avail = 1;
756     }
757     if (!iommu->g_iota) {
758         error = ERR_EVENT_INVALAS;
759         goto err;
760     }
761 
762     if (end < iommu->pba || start > iommu->pal) {
763         error = ERR_EVENT_OORANGE;
764         goto err;
765     }
766 
767  retry:
768     start = sstart;
769     again = false;
770     while (start < end) {
771         error = s390_guest_io_table_walk(iommu->g_iota, start, &entry);
772         if (error) {
773             break;
774         }
775 
776         /*
777          * If this is an unmap of a PTE, let's try to coalesce multiple unmaps
778          * into as few notifier events as possible.
779          */
780         if (entry.perm == IOMMU_NONE && entry.len == TARGET_PAGE_SIZE) {
781             if (coalesce == 0) {
782                 iova = entry.iova;
783             }
784             coalesce += entry.len;
785         } else if (coalesce > 0) {
786             /* Unleash the coalesced unmap before processing a new map */
787             s390_pci_batch_unmap(iommu, iova, coalesce);
788             coalesce = 0;
789         }
790 
791         start += entry.len;
792         while (entry.iova < start && entry.iova < end) {
793             if (dma_avail > 0 || entry.perm == IOMMU_NONE) {
794                 dma_avail = s390_pci_update_iotlb(iommu, &entry);
795                 entry.iova += TARGET_PAGE_SIZE;
796                 entry.translated_addr += TARGET_PAGE_SIZE;
797             } else {
798                 /*
799                  * We are unable to make a new mapping at this time, continue
800                  * on and hopefully free up more space.  Then attempt another
801                  * pass.
802                  */
803                 again = true;
804                 break;
805             }
806         }
807     }
808     if (coalesce) {
809             /* Unleash the coalesced unmap before finishing rpcit */
810             s390_pci_batch_unmap(iommu, iova, coalesce);
811             coalesce = 0;
812     }
813     if (again && dma_avail > 0)
814         goto retry;
815 err:
816     if (error) {
817         pbdev->state = ZPCI_FS_ERROR;
818         setcc(cpu, ZPCI_PCI_LS_ERR);
819         s390_set_status_code(env, r1, ZPCI_PCI_ST_FUNC_IN_ERR);
820         s390_pci_generate_error_event(error, pbdev->fh, pbdev->fid, start, 0);
821     } else {
822         pbdev->fmb.counter[ZPCI_FMB_CNT_RPCIT]++;
823         if (dma_avail > 0) {
824             setcc(cpu, ZPCI_PCI_LS_OK);
825         } else {
826             /* vfio DMA mappings are exhausted, trigger a RPCIT */
827             setcc(cpu, ZPCI_PCI_LS_ERR);
828             s390_set_status_code(env, r1, ZPCI_RPCIT_ST_INSUFF_RES);
829         }
830     }
831     return 0;
832 }
833 
834 int pcistb_service_call(S390CPU *cpu, uint8_t r1, uint8_t r3, uint64_t gaddr,
835                         uint8_t ar, uintptr_t ra)
836 {
837     CPUS390XState *env = &cpu->env;
838     S390PCIBusDevice *pbdev;
839     MemoryRegion *mr;
840     MemTxResult result;
841     uint64_t offset;
842     int i;
843     uint32_t fh;
844     uint8_t pcias;
845     uint16_t len;
846     uint8_t buffer[128];
847 
848     if (env->psw.mask & PSW_MASK_PSTATE) {
849         s390_program_interrupt(env, PGM_PRIVILEGED, ra);
850         return 0;
851     }
852 
853     fh = env->regs[r1] >> 32;
854     pcias = (env->regs[r1] >> 16) & 0xf;
855     len = env->regs[r1] & 0x1fff;
856     offset = env->regs[r3];
857 
858     if (!(fh & FH_MASK_ENABLE)) {
859         setcc(cpu, ZPCI_PCI_LS_INVAL_HANDLE);
860         return 0;
861     }
862 
863     pbdev = s390_pci_find_dev_by_fh(s390_get_phb(), fh);
864     if (!pbdev) {
865         DPRINTF("pcistb no pci dev fh 0x%x\n", fh);
866         setcc(cpu, ZPCI_PCI_LS_INVAL_HANDLE);
867         return 0;
868     }
869 
870     switch (pbdev->state) {
871     case ZPCI_FS_PERMANENT_ERROR:
872     case ZPCI_FS_ERROR:
873         setcc(cpu, ZPCI_PCI_LS_ERR);
874         s390_set_status_code(env, r1, ZPCI_PCI_ST_BLOCKED);
875         return 0;
876     default:
877         break;
878     }
879 
880     if (pcias > ZPCI_IO_BAR_MAX) {
881         DPRINTF("pcistb invalid space\n");
882         setcc(cpu, ZPCI_PCI_LS_ERR);
883         s390_set_status_code(env, r1, ZPCI_PCI_ST_INVAL_AS);
884         return 0;
885     }
886 
887     /* Verify the address, offset and length */
888     /* offset must be a multiple of 8 */
889     if (offset % 8) {
890         goto specification_error;
891     }
892     /* Length must be greater than 8, a multiple of 8 */
893     /* and not greater than maxstbl */
894     if ((len <= 8) || (len % 8) ||
895         (len > pbdev->pci_group->zpci_group.maxstbl)) {
896         goto specification_error;
897     }
898     /* Do not cross a 4K-byte boundary */
899     if (((offset & 0xfff) + len) > 0x1000) {
900         goto specification_error;
901     }
902     /* Guest address must be double word aligned */
903     if (gaddr & 0x07UL) {
904         goto specification_error;
905     }
906 
907     mr = pbdev->pdev->io_regions[pcias].memory;
908     mr = s390_get_subregion(mr, offset, len);
909     offset -= mr->addr;
910 
911     for (i = 0; i < len; i += 8) {
912         if (!memory_region_access_valid(mr, offset + i, 8, true,
913                                         MEMTXATTRS_UNSPECIFIED)) {
914             s390_program_interrupt(env, PGM_OPERAND, ra);
915             return 0;
916         }
917     }
918 
919     if (s390_cpu_virt_mem_read(cpu, gaddr, ar, buffer, len)) {
920         s390_cpu_virt_mem_handle_exc(cpu, ra);
921         return 0;
922     }
923 
924     for (i = 0; i < len / 8; i++) {
925         result = memory_region_dispatch_write(mr, offset + i * 8,
926                                               ldq_p(buffer + i * 8),
927                                               MO_64, MEMTXATTRS_UNSPECIFIED);
928         if (result != MEMTX_OK) {
929             s390_program_interrupt(env, PGM_OPERAND, ra);
930             return 0;
931         }
932     }
933 
934     pbdev->fmb.counter[ZPCI_FMB_CNT_STB]++;
935 
936     setcc(cpu, ZPCI_PCI_LS_OK);
937     return 0;
938 
939 specification_error:
940     s390_program_interrupt(env, PGM_SPECIFICATION, ra);
941     return 0;
942 }
943 
944 static int reg_irqs(CPUS390XState *env, S390PCIBusDevice *pbdev, ZpciFib fib)
945 {
946     int ret, len;
947     uint8_t isc = FIB_DATA_ISC(ldl_p(&fib.data));
948 
949     pbdev->routes.adapter.adapter_id = css_get_adapter_id(
950                                        CSS_IO_ADAPTER_PCI, isc);
951     pbdev->summary_ind = get_indicator(ldq_p(&fib.aisb), sizeof(uint64_t));
952     len = BITS_TO_LONGS(FIB_DATA_NOI(ldl_p(&fib.data))) * sizeof(unsigned long);
953     pbdev->indicator = get_indicator(ldq_p(&fib.aibv), len);
954 
955     ret = map_indicator(&pbdev->routes.adapter, pbdev->summary_ind);
956     if (ret) {
957         goto out;
958     }
959 
960     ret = map_indicator(&pbdev->routes.adapter, pbdev->indicator);
961     if (ret) {
962         goto out;
963     }
964 
965     pbdev->routes.adapter.summary_addr = ldq_p(&fib.aisb);
966     pbdev->routes.adapter.summary_offset = FIB_DATA_AISBO(ldl_p(&fib.data));
967     pbdev->routes.adapter.ind_addr = ldq_p(&fib.aibv);
968     pbdev->routes.adapter.ind_offset = FIB_DATA_AIBVO(ldl_p(&fib.data));
969     pbdev->isc = isc;
970     pbdev->noi = FIB_DATA_NOI(ldl_p(&fib.data));
971     pbdev->sum = FIB_DATA_SUM(ldl_p(&fib.data));
972 
973     DPRINTF("reg_irqs adapter id %d\n", pbdev->routes.adapter.adapter_id);
974     return 0;
975 out:
976     release_indicator(&pbdev->routes.adapter, pbdev->summary_ind);
977     release_indicator(&pbdev->routes.adapter, pbdev->indicator);
978     pbdev->summary_ind = NULL;
979     pbdev->indicator = NULL;
980     return ret;
981 }
982 
983 int pci_dereg_irqs(S390PCIBusDevice *pbdev)
984 {
985     release_indicator(&pbdev->routes.adapter, pbdev->summary_ind);
986     release_indicator(&pbdev->routes.adapter, pbdev->indicator);
987 
988     pbdev->summary_ind = NULL;
989     pbdev->indicator = NULL;
990     pbdev->routes.adapter.summary_addr = 0;
991     pbdev->routes.adapter.summary_offset = 0;
992     pbdev->routes.adapter.ind_addr = 0;
993     pbdev->routes.adapter.ind_offset = 0;
994     pbdev->isc = 0;
995     pbdev->noi = 0;
996     pbdev->sum = 0;
997 
998     DPRINTF("dereg_irqs adapter id %d\n", pbdev->routes.adapter.adapter_id);
999     return 0;
1000 }
1001 
1002 static int reg_ioat(CPUS390XState *env, S390PCIBusDevice *pbdev, ZpciFib fib,
1003                     uintptr_t ra)
1004 {
1005     S390PCIIOMMU *iommu = pbdev->iommu;
1006     uint64_t pba = ldq_p(&fib.pba);
1007     uint64_t pal = ldq_p(&fib.pal);
1008     uint64_t g_iota = ldq_p(&fib.iota);
1009     uint8_t dt = (g_iota >> 2) & 0x7;
1010     uint8_t t = (g_iota >> 11) & 0x1;
1011 
1012     pba &= ~0xfff;
1013     pal |= 0xfff;
1014     if (pba > pal || pba < pbdev->zpci_fn.sdma || pal > pbdev->zpci_fn.edma) {
1015         s390_program_interrupt(env, PGM_OPERAND, ra);
1016         return -EINVAL;
1017     }
1018 
1019     /* currently we only support designation type 1 with translation */
1020     if (!(dt == ZPCI_IOTA_RTTO && t)) {
1021         error_report("unsupported ioat dt %d t %d", dt, t);
1022         s390_program_interrupt(env, PGM_OPERAND, ra);
1023         return -EINVAL;
1024     }
1025 
1026     iommu->pba = pba;
1027     iommu->pal = pal;
1028     iommu->g_iota = g_iota;
1029 
1030     s390_pci_iommu_enable(iommu);
1031 
1032     return 0;
1033 }
1034 
1035 void pci_dereg_ioat(S390PCIIOMMU *iommu)
1036 {
1037     s390_pci_iommu_disable(iommu);
1038     iommu->pba = 0;
1039     iommu->pal = 0;
1040     iommu->g_iota = 0;
1041 }
1042 
1043 void fmb_timer_free(S390PCIBusDevice *pbdev)
1044 {
1045     if (pbdev->fmb_timer) {
1046         timer_free(pbdev->fmb_timer);
1047         pbdev->fmb_timer = NULL;
1048     }
1049     pbdev->fmb_addr = 0;
1050     memset(&pbdev->fmb, 0, sizeof(ZpciFmb));
1051 }
1052 
1053 static int fmb_do_update(S390PCIBusDevice *pbdev, int offset, uint64_t val,
1054                          int len)
1055 {
1056     MemTxResult ret;
1057     uint64_t dst = pbdev->fmb_addr + offset;
1058 
1059     switch (len) {
1060     case 8:
1061         address_space_stq_be(&address_space_memory, dst, val,
1062                              MEMTXATTRS_UNSPECIFIED,
1063                              &ret);
1064         break;
1065     case 4:
1066         address_space_stl_be(&address_space_memory, dst, val,
1067                              MEMTXATTRS_UNSPECIFIED,
1068                              &ret);
1069         break;
1070     case 2:
1071         address_space_stw_be(&address_space_memory, dst, val,
1072                              MEMTXATTRS_UNSPECIFIED,
1073                              &ret);
1074         break;
1075     case 1:
1076         address_space_stb(&address_space_memory, dst, val,
1077                           MEMTXATTRS_UNSPECIFIED,
1078                           &ret);
1079         break;
1080     default:
1081         ret = MEMTX_ERROR;
1082         break;
1083     }
1084     if (ret != MEMTX_OK) {
1085         s390_pci_generate_error_event(ERR_EVENT_FMBA, pbdev->fh, pbdev->fid,
1086                                       pbdev->fmb_addr, 0);
1087         fmb_timer_free(pbdev);
1088     }
1089 
1090     return ret;
1091 }
1092 
1093 static void fmb_update(void *opaque)
1094 {
1095     S390PCIBusDevice *pbdev = opaque;
1096     int64_t t = qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL);
1097     int i;
1098 
1099     /* Update U bit */
1100     pbdev->fmb.last_update *= 2;
1101     pbdev->fmb.last_update |= UPDATE_U_BIT;
1102     if (fmb_do_update(pbdev, offsetof(ZpciFmb, last_update),
1103                       pbdev->fmb.last_update,
1104                       sizeof(pbdev->fmb.last_update))) {
1105         return;
1106     }
1107 
1108     /* Update FMB sample count */
1109     if (fmb_do_update(pbdev, offsetof(ZpciFmb, sample),
1110                       pbdev->fmb.sample++,
1111                       sizeof(pbdev->fmb.sample))) {
1112         return;
1113     }
1114 
1115     /* Update FMB counters */
1116     for (i = 0; i < ZPCI_FMB_CNT_MAX; i++) {
1117         if (fmb_do_update(pbdev, offsetof(ZpciFmb, counter[i]),
1118                           pbdev->fmb.counter[i],
1119                           sizeof(pbdev->fmb.counter[0]))) {
1120             return;
1121         }
1122     }
1123 
1124     /* Clear U bit and update the time */
1125     pbdev->fmb.last_update = time2tod(qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL));
1126     pbdev->fmb.last_update *= 2;
1127     if (fmb_do_update(pbdev, offsetof(ZpciFmb, last_update),
1128                       pbdev->fmb.last_update,
1129                       sizeof(pbdev->fmb.last_update))) {
1130         return;
1131     }
1132     timer_mod(pbdev->fmb_timer, t + pbdev->pci_group->zpci_group.mui);
1133 }
1134 
1135 static int mpcifc_reg_int_interp(S390PCIBusDevice *pbdev, ZpciFib *fib)
1136 {
1137     int rc;
1138 
1139     rc = s390_pci_kvm_aif_enable(pbdev, fib, pbdev->forwarding_assist);
1140     if (rc) {
1141         DPRINTF("Failed to enable interrupt forwarding\n");
1142         return rc;
1143     }
1144 
1145     return 0;
1146 }
1147 
1148 static int mpcifc_dereg_int_interp(S390PCIBusDevice *pbdev, ZpciFib *fib)
1149 {
1150     int rc;
1151 
1152     rc = s390_pci_kvm_aif_disable(pbdev);
1153     if (rc) {
1154         DPRINTF("Failed to disable interrupt forwarding\n");
1155         return rc;
1156     }
1157 
1158     return 0;
1159 }
1160 
1161 int mpcifc_service_call(S390CPU *cpu, uint8_t r1, uint64_t fiba, uint8_t ar,
1162                         uintptr_t ra)
1163 {
1164     CPUS390XState *env = &cpu->env;
1165     uint8_t oc, dmaas;
1166     uint32_t fh;
1167     ZpciFib fib;
1168     S390PCIBusDevice *pbdev;
1169     uint64_t cc = ZPCI_PCI_LS_OK;
1170 
1171     if (env->psw.mask & PSW_MASK_PSTATE) {
1172         s390_program_interrupt(env, PGM_PRIVILEGED, ra);
1173         return 0;
1174     }
1175 
1176     oc = env->regs[r1] & 0xff;
1177     dmaas = (env->regs[r1] >> 16) & 0xff;
1178     fh = env->regs[r1] >> 32;
1179 
1180     if (fiba & 0x7) {
1181         s390_program_interrupt(env, PGM_SPECIFICATION, ra);
1182         return 0;
1183     }
1184 
1185     pbdev = s390_pci_find_dev_by_fh(s390_get_phb(), fh);
1186     if (!pbdev) {
1187         DPRINTF("mpcifc no pci dev fh 0x%x\n", fh);
1188         setcc(cpu, ZPCI_PCI_LS_INVAL_HANDLE);
1189         return 0;
1190     }
1191 
1192     switch (pbdev->state) {
1193     case ZPCI_FS_RESERVED:
1194     case ZPCI_FS_STANDBY:
1195     case ZPCI_FS_DISABLED:
1196     case ZPCI_FS_PERMANENT_ERROR:
1197         setcc(cpu, ZPCI_PCI_LS_INVAL_HANDLE);
1198         return 0;
1199     default:
1200         break;
1201     }
1202 
1203     if (s390_cpu_virt_mem_read(cpu, fiba, ar, (uint8_t *)&fib, sizeof(fib))) {
1204         s390_cpu_virt_mem_handle_exc(cpu, ra);
1205         return 0;
1206     }
1207 
1208     if (fib.fmt != 0) {
1209         s390_program_interrupt(env, PGM_OPERAND, ra);
1210         return 0;
1211     }
1212 
1213     switch (oc) {
1214     case ZPCI_MOD_FC_REG_INT:
1215         if (pbdev->interp) {
1216             if (mpcifc_reg_int_interp(pbdev, &fib)) {
1217                 cc = ZPCI_PCI_LS_ERR;
1218                 s390_set_status_code(env, r1, ZPCI_MOD_ST_SEQUENCE);
1219             }
1220         } else if (pbdev->summary_ind) {
1221             cc = ZPCI_PCI_LS_ERR;
1222             s390_set_status_code(env, r1, ZPCI_MOD_ST_SEQUENCE);
1223         } else if (reg_irqs(env, pbdev, fib)) {
1224             cc = ZPCI_PCI_LS_ERR;
1225             s390_set_status_code(env, r1, ZPCI_MOD_ST_RES_NOT_AVAIL);
1226         }
1227         break;
1228     case ZPCI_MOD_FC_DEREG_INT:
1229         if (pbdev->interp) {
1230             if (mpcifc_dereg_int_interp(pbdev, &fib)) {
1231                 cc = ZPCI_PCI_LS_ERR;
1232                 s390_set_status_code(env, r1, ZPCI_MOD_ST_SEQUENCE);
1233             }
1234         } else if (!pbdev->summary_ind) {
1235             cc = ZPCI_PCI_LS_ERR;
1236             s390_set_status_code(env, r1, ZPCI_MOD_ST_SEQUENCE);
1237         } else {
1238             pci_dereg_irqs(pbdev);
1239         }
1240         break;
1241     case ZPCI_MOD_FC_REG_IOAT:
1242         if (dmaas != 0) {
1243             cc = ZPCI_PCI_LS_ERR;
1244             s390_set_status_code(env, r1, ZPCI_MOD_ST_DMAAS_INVAL);
1245         } else if (pbdev->iommu->enabled) {
1246             cc = ZPCI_PCI_LS_ERR;
1247             s390_set_status_code(env, r1, ZPCI_MOD_ST_SEQUENCE);
1248         } else if (reg_ioat(env, pbdev, fib, ra)) {
1249             cc = ZPCI_PCI_LS_ERR;
1250             s390_set_status_code(env, r1, ZPCI_MOD_ST_INSUF_RES);
1251         }
1252         break;
1253     case ZPCI_MOD_FC_DEREG_IOAT:
1254         if (dmaas != 0) {
1255             cc = ZPCI_PCI_LS_ERR;
1256             s390_set_status_code(env, r1, ZPCI_MOD_ST_DMAAS_INVAL);
1257         } else if (!pbdev->iommu->enabled) {
1258             cc = ZPCI_PCI_LS_ERR;
1259             s390_set_status_code(env, r1, ZPCI_MOD_ST_SEQUENCE);
1260         } else {
1261             pci_dereg_ioat(pbdev->iommu);
1262         }
1263         break;
1264     case ZPCI_MOD_FC_REREG_IOAT:
1265         if (dmaas != 0) {
1266             cc = ZPCI_PCI_LS_ERR;
1267             s390_set_status_code(env, r1, ZPCI_MOD_ST_DMAAS_INVAL);
1268         } else if (!pbdev->iommu->enabled) {
1269             cc = ZPCI_PCI_LS_ERR;
1270             s390_set_status_code(env, r1, ZPCI_MOD_ST_SEQUENCE);
1271         } else {
1272             pci_dereg_ioat(pbdev->iommu);
1273             if (reg_ioat(env, pbdev, fib, ra)) {
1274                 cc = ZPCI_PCI_LS_ERR;
1275                 s390_set_status_code(env, r1, ZPCI_MOD_ST_INSUF_RES);
1276             }
1277         }
1278         break;
1279     case ZPCI_MOD_FC_RESET_ERROR:
1280         switch (pbdev->state) {
1281         case ZPCI_FS_BLOCKED:
1282         case ZPCI_FS_ERROR:
1283             pbdev->state = ZPCI_FS_ENABLED;
1284             break;
1285         default:
1286             cc = ZPCI_PCI_LS_ERR;
1287             s390_set_status_code(env, r1, ZPCI_MOD_ST_SEQUENCE);
1288         }
1289         break;
1290     case ZPCI_MOD_FC_RESET_BLOCK:
1291         switch (pbdev->state) {
1292         case ZPCI_FS_ERROR:
1293             pbdev->state = ZPCI_FS_BLOCKED;
1294             break;
1295         default:
1296             cc = ZPCI_PCI_LS_ERR;
1297             s390_set_status_code(env, r1, ZPCI_MOD_ST_SEQUENCE);
1298         }
1299         break;
1300     case ZPCI_MOD_FC_SET_MEASURE: {
1301         uint64_t fmb_addr = ldq_p(&fib.fmb_addr);
1302 
1303         if (fmb_addr & FMBK_MASK) {
1304             cc = ZPCI_PCI_LS_ERR;
1305             s390_pci_generate_error_event(ERR_EVENT_FMBPRO, pbdev->fh,
1306                                           pbdev->fid, fmb_addr, 0);
1307             fmb_timer_free(pbdev);
1308             break;
1309         }
1310 
1311         if (!fmb_addr) {
1312             /* Stop updating FMB. */
1313             fmb_timer_free(pbdev);
1314             break;
1315         }
1316 
1317         if (!pbdev->fmb_timer) {
1318             pbdev->fmb_timer = timer_new_ms(QEMU_CLOCK_VIRTUAL,
1319                                             fmb_update, pbdev);
1320         } else if (timer_pending(pbdev->fmb_timer)) {
1321             /* Remove pending timer to update FMB address. */
1322             timer_del(pbdev->fmb_timer);
1323         }
1324         pbdev->fmb_addr = fmb_addr;
1325         timer_mod(pbdev->fmb_timer,
1326                   qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) +
1327                                     pbdev->pci_group->zpci_group.mui);
1328         break;
1329     }
1330     default:
1331         s390_program_interrupt(&cpu->env, PGM_OPERAND, ra);
1332         cc = ZPCI_PCI_LS_ERR;
1333     }
1334 
1335     setcc(cpu, cc);
1336     return 0;
1337 }
1338 
1339 int stpcifc_service_call(S390CPU *cpu, uint8_t r1, uint64_t fiba, uint8_t ar,
1340                          uintptr_t ra)
1341 {
1342     CPUS390XState *env = &cpu->env;
1343     uint8_t dmaas;
1344     uint32_t fh;
1345     ZpciFib fib;
1346     S390PCIBusDevice *pbdev;
1347     uint32_t data;
1348     uint64_t cc = ZPCI_PCI_LS_OK;
1349 
1350     if (env->psw.mask & PSW_MASK_PSTATE) {
1351         s390_program_interrupt(env, PGM_PRIVILEGED, ra);
1352         return 0;
1353     }
1354 
1355     fh = env->regs[r1] >> 32;
1356     dmaas = (env->regs[r1] >> 16) & 0xff;
1357 
1358     if (dmaas) {
1359         setcc(cpu, ZPCI_PCI_LS_ERR);
1360         s390_set_status_code(env, r1, ZPCI_STPCIFC_ST_INVAL_DMAAS);
1361         return 0;
1362     }
1363 
1364     if (fiba & 0x7) {
1365         s390_program_interrupt(env, PGM_SPECIFICATION, ra);
1366         return 0;
1367     }
1368 
1369     pbdev = s390_pci_find_dev_by_idx(s390_get_phb(), fh & FH_MASK_INDEX);
1370     if (!pbdev) {
1371         setcc(cpu, ZPCI_PCI_LS_INVAL_HANDLE);
1372         return 0;
1373     }
1374 
1375     memset(&fib, 0, sizeof(fib));
1376 
1377     switch (pbdev->state) {
1378     case ZPCI_FS_RESERVED:
1379     case ZPCI_FS_STANDBY:
1380         setcc(cpu, ZPCI_PCI_LS_INVAL_HANDLE);
1381         return 0;
1382     case ZPCI_FS_DISABLED:
1383         if (fh & FH_MASK_ENABLE) {
1384             setcc(cpu, ZPCI_PCI_LS_INVAL_HANDLE);
1385             return 0;
1386         }
1387         goto out;
1388     /* BLOCKED bit is set to one coincident with the setting of ERROR bit.
1389      * FH Enabled bit is set to one in states of ENABLED, BLOCKED or ERROR. */
1390     case ZPCI_FS_ERROR:
1391         fib.fc |= 0x20;
1392         /* fallthrough */
1393     case ZPCI_FS_BLOCKED:
1394         fib.fc |= 0x40;
1395         /* fallthrough */
1396     case ZPCI_FS_ENABLED:
1397         fib.fc |= 0x80;
1398         if (pbdev->iommu->enabled) {
1399             fib.fc |= 0x10;
1400         }
1401         if (!(fh & FH_MASK_ENABLE)) {
1402             env->regs[r1] |= 1ULL << 63;
1403         }
1404         break;
1405     case ZPCI_FS_PERMANENT_ERROR:
1406         setcc(cpu, ZPCI_PCI_LS_ERR);
1407         s390_set_status_code(env, r1, ZPCI_STPCIFC_ST_PERM_ERROR);
1408         return 0;
1409     }
1410 
1411     stq_p(&fib.pba, pbdev->iommu->pba);
1412     stq_p(&fib.pal, pbdev->iommu->pal);
1413     stq_p(&fib.iota, pbdev->iommu->g_iota);
1414     stq_p(&fib.aibv, pbdev->routes.adapter.ind_addr);
1415     stq_p(&fib.aisb, pbdev->routes.adapter.summary_addr);
1416     stq_p(&fib.fmb_addr, pbdev->fmb_addr);
1417 
1418     data = ((uint32_t)pbdev->isc << 28) | ((uint32_t)pbdev->noi << 16) |
1419            ((uint32_t)pbdev->routes.adapter.ind_offset << 8) |
1420            ((uint32_t)pbdev->sum << 7) | pbdev->routes.adapter.summary_offset;
1421     stl_p(&fib.data, data);
1422 
1423 out:
1424     if (s390_cpu_virt_mem_write(cpu, fiba, ar, (uint8_t *)&fib, sizeof(fib))) {
1425         s390_cpu_virt_mem_handle_exc(cpu, ra);
1426         return 0;
1427     }
1428 
1429     setcc(cpu, cc);
1430     return 0;
1431 }
1432