xref: /qemu/target/s390x/kvm/kvm.c (revision cf729baaec3fceff31ea8f41e34fbc7e2475916d)
1 /*
2  * QEMU S390x KVM implementation
3  *
4  * Copyright (c) 2009 Alexander Graf <agraf@suse.de>
5  * Copyright IBM Corp. 2012
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * Contributions after 2012-10-29 are licensed under the terms of the
18  * GNU GPL, version 2 or (at your option) any later version.
19  *
20  * You should have received a copy of the GNU (Lesser) General Public
21  * License along with this library; if not, see <http://www.gnu.org/licenses/>.
22  */
23 
24 #include "qemu/osdep.h"
25 #include <sys/ioctl.h>
26 
27 #include <linux/kvm.h>
28 #include <asm/ptrace.h>
29 
30 #include "qemu-common.h"
31 #include "cpu.h"
32 #include "internal.h"
33 #include "kvm_s390x.h"
34 #include "qemu/error-report.h"
35 #include "qemu/timer.h"
36 #include "sysemu/sysemu.h"
37 #include "sysemu/hw_accel.h"
38 #include "hw/hw.h"
39 #include "sysemu/device_tree.h"
40 #include "qapi/qmp/qjson.h"
41 #include "exec/gdbstub.h"
42 #include "exec/address-spaces.h"
43 #include "trace.h"
44 #include "qapi-event.h"
45 #include "hw/s390x/s390-pci-inst.h"
46 #include "hw/s390x/s390-pci-bus.h"
47 #include "hw/s390x/ipl.h"
48 #include "hw/s390x/ebcdic.h"
49 #include "exec/memattrs.h"
50 #include "hw/s390x/s390-virtio-ccw.h"
51 #include "hw/s390x/s390-virtio-hcall.h"
52 
53 #ifndef DEBUG_KVM
54 #define DEBUG_KVM  0
55 #endif
56 
57 #define DPRINTF(fmt, ...) do {                \
58     if (DEBUG_KVM) {                          \
59         fprintf(stderr, fmt, ## __VA_ARGS__); \
60     }                                         \
61 } while (0);
62 
63 #define kvm_vm_check_mem_attr(s, attr) \
64     kvm_vm_check_attr(s, KVM_S390_VM_MEM_CTRL, attr)
65 
66 #define IPA0_DIAG                       0x8300
67 #define IPA0_SIGP                       0xae00
68 #define IPA0_B2                         0xb200
69 #define IPA0_B9                         0xb900
70 #define IPA0_EB                         0xeb00
71 #define IPA0_E3                         0xe300
72 
73 #define PRIV_B2_SCLP_CALL               0x20
74 #define PRIV_B2_CSCH                    0x30
75 #define PRIV_B2_HSCH                    0x31
76 #define PRIV_B2_MSCH                    0x32
77 #define PRIV_B2_SSCH                    0x33
78 #define PRIV_B2_STSCH                   0x34
79 #define PRIV_B2_TSCH                    0x35
80 #define PRIV_B2_TPI                     0x36
81 #define PRIV_B2_SAL                     0x37
82 #define PRIV_B2_RSCH                    0x38
83 #define PRIV_B2_STCRW                   0x39
84 #define PRIV_B2_STCPS                   0x3a
85 #define PRIV_B2_RCHP                    0x3b
86 #define PRIV_B2_SCHM                    0x3c
87 #define PRIV_B2_CHSC                    0x5f
88 #define PRIV_B2_SIGA                    0x74
89 #define PRIV_B2_XSCH                    0x76
90 
91 #define PRIV_EB_SQBS                    0x8a
92 #define PRIV_EB_PCISTB                  0xd0
93 #define PRIV_EB_SIC                     0xd1
94 
95 #define PRIV_B9_EQBS                    0x9c
96 #define PRIV_B9_CLP                     0xa0
97 #define PRIV_B9_PCISTG                  0xd0
98 #define PRIV_B9_PCILG                   0xd2
99 #define PRIV_B9_RPCIT                   0xd3
100 
101 #define PRIV_E3_MPCIFC                  0xd0
102 #define PRIV_E3_STPCIFC                 0xd4
103 
104 #define DIAG_TIMEREVENT                 0x288
105 #define DIAG_IPL                        0x308
106 #define DIAG_KVM_HYPERCALL              0x500
107 #define DIAG_KVM_BREAKPOINT             0x501
108 
109 #define ICPT_INSTRUCTION                0x04
110 #define ICPT_PROGRAM                    0x08
111 #define ICPT_EXT_INT                    0x14
112 #define ICPT_WAITPSW                    0x1c
113 #define ICPT_SOFT_INTERCEPT             0x24
114 #define ICPT_CPU_STOP                   0x28
115 #define ICPT_OPEREXC                    0x2c
116 #define ICPT_IO                         0x40
117 
118 #define NR_LOCAL_IRQS 32
119 /*
120  * Needs to be big enough to contain max_cpus emergency signals
121  * and in addition NR_LOCAL_IRQS interrupts
122  */
123 #define VCPU_IRQ_BUF_SIZE (sizeof(struct kvm_s390_irq) * \
124                            (max_cpus + NR_LOCAL_IRQS))
125 
126 static CPUWatchpoint hw_watchpoint;
127 /*
128  * We don't use a list because this structure is also used to transmit the
129  * hardware breakpoints to the kernel.
130  */
131 static struct kvm_hw_breakpoint *hw_breakpoints;
132 static int nb_hw_breakpoints;
133 
134 const KVMCapabilityInfo kvm_arch_required_capabilities[] = {
135     KVM_CAP_LAST_INFO
136 };
137 
138 static QemuMutex qemu_sigp_mutex;
139 
140 static int cap_sync_regs;
141 static int cap_async_pf;
142 static int cap_mem_op;
143 static int cap_s390_irq;
144 static int cap_ri;
145 static int cap_gs;
146 
147 static int active_cmma;
148 
149 static void *legacy_s390_alloc(size_t size, uint64_t *align);
150 
151 static int kvm_s390_query_mem_limit(uint64_t *memory_limit)
152 {
153     struct kvm_device_attr attr = {
154         .group = KVM_S390_VM_MEM_CTRL,
155         .attr = KVM_S390_VM_MEM_LIMIT_SIZE,
156         .addr = (uint64_t) memory_limit,
157     };
158 
159     return kvm_vm_ioctl(kvm_state, KVM_GET_DEVICE_ATTR, &attr);
160 }
161 
162 int kvm_s390_set_mem_limit(uint64_t new_limit, uint64_t *hw_limit)
163 {
164     int rc;
165 
166     struct kvm_device_attr attr = {
167         .group = KVM_S390_VM_MEM_CTRL,
168         .attr = KVM_S390_VM_MEM_LIMIT_SIZE,
169         .addr = (uint64_t) &new_limit,
170     };
171 
172     if (!kvm_vm_check_mem_attr(kvm_state, KVM_S390_VM_MEM_LIMIT_SIZE)) {
173         return 0;
174     }
175 
176     rc = kvm_s390_query_mem_limit(hw_limit);
177     if (rc) {
178         return rc;
179     } else if (*hw_limit < new_limit) {
180         return -E2BIG;
181     }
182 
183     return kvm_vm_ioctl(kvm_state, KVM_SET_DEVICE_ATTR, &attr);
184 }
185 
186 int kvm_s390_cmma_active(void)
187 {
188     return active_cmma;
189 }
190 
191 static bool kvm_s390_cmma_available(void)
192 {
193     static bool initialized, value;
194 
195     if (!initialized) {
196         initialized = true;
197         value = kvm_vm_check_mem_attr(kvm_state, KVM_S390_VM_MEM_ENABLE_CMMA) &&
198                 kvm_vm_check_mem_attr(kvm_state, KVM_S390_VM_MEM_CLR_CMMA);
199     }
200     return value;
201 }
202 
203 void kvm_s390_cmma_reset(void)
204 {
205     int rc;
206     struct kvm_device_attr attr = {
207         .group = KVM_S390_VM_MEM_CTRL,
208         .attr = KVM_S390_VM_MEM_CLR_CMMA,
209     };
210 
211     if (!kvm_s390_cmma_active()) {
212         return;
213     }
214 
215     rc = kvm_vm_ioctl(kvm_state, KVM_SET_DEVICE_ATTR, &attr);
216     trace_kvm_clear_cmma(rc);
217 }
218 
219 static void kvm_s390_enable_cmma(void)
220 {
221     int rc;
222     struct kvm_device_attr attr = {
223         .group = KVM_S390_VM_MEM_CTRL,
224         .attr = KVM_S390_VM_MEM_ENABLE_CMMA,
225     };
226 
227     if (mem_path) {
228         warn_report("CMM will not be enabled because it is not "
229                     "compatible with hugetlbfs.");
230         return;
231     }
232     rc = kvm_vm_ioctl(kvm_state, KVM_SET_DEVICE_ATTR, &attr);
233     active_cmma = !rc;
234     trace_kvm_enable_cmma(rc);
235 }
236 
237 static void kvm_s390_set_attr(uint64_t attr)
238 {
239     struct kvm_device_attr attribute = {
240         .group = KVM_S390_VM_CRYPTO,
241         .attr  = attr,
242     };
243 
244     int ret = kvm_vm_ioctl(kvm_state, KVM_SET_DEVICE_ATTR, &attribute);
245 
246     if (ret) {
247         error_report("Failed to set crypto device attribute %lu: %s",
248                      attr, strerror(-ret));
249     }
250 }
251 
252 static void kvm_s390_init_aes_kw(void)
253 {
254     uint64_t attr = KVM_S390_VM_CRYPTO_DISABLE_AES_KW;
255 
256     if (object_property_get_bool(OBJECT(qdev_get_machine()), "aes-key-wrap",
257                                  NULL)) {
258             attr = KVM_S390_VM_CRYPTO_ENABLE_AES_KW;
259     }
260 
261     if (kvm_vm_check_attr(kvm_state, KVM_S390_VM_CRYPTO, attr)) {
262             kvm_s390_set_attr(attr);
263     }
264 }
265 
266 static void kvm_s390_init_dea_kw(void)
267 {
268     uint64_t attr = KVM_S390_VM_CRYPTO_DISABLE_DEA_KW;
269 
270     if (object_property_get_bool(OBJECT(qdev_get_machine()), "dea-key-wrap",
271                                  NULL)) {
272             attr = KVM_S390_VM_CRYPTO_ENABLE_DEA_KW;
273     }
274 
275     if (kvm_vm_check_attr(kvm_state, KVM_S390_VM_CRYPTO, attr)) {
276             kvm_s390_set_attr(attr);
277     }
278 }
279 
280 void kvm_s390_crypto_reset(void)
281 {
282     if (s390_has_feat(S390_FEAT_MSA_EXT_3)) {
283         kvm_s390_init_aes_kw();
284         kvm_s390_init_dea_kw();
285     }
286 }
287 
288 int kvm_arch_init(MachineState *ms, KVMState *s)
289 {
290     MachineClass *mc = MACHINE_GET_CLASS(ms);
291 
292     mc->default_cpu_type = S390_CPU_TYPE_NAME("host");
293     cap_sync_regs = kvm_check_extension(s, KVM_CAP_SYNC_REGS);
294     cap_async_pf = kvm_check_extension(s, KVM_CAP_ASYNC_PF);
295     cap_mem_op = kvm_check_extension(s, KVM_CAP_S390_MEM_OP);
296     cap_s390_irq = kvm_check_extension(s, KVM_CAP_S390_INJECT_IRQ);
297 
298     if (!kvm_check_extension(s, KVM_CAP_S390_GMAP)
299         || !kvm_check_extension(s, KVM_CAP_S390_COW)) {
300         phys_mem_set_alloc(legacy_s390_alloc);
301     }
302 
303     kvm_vm_enable_cap(s, KVM_CAP_S390_USER_SIGP, 0);
304     kvm_vm_enable_cap(s, KVM_CAP_S390_VECTOR_REGISTERS, 0);
305     kvm_vm_enable_cap(s, KVM_CAP_S390_USER_STSI, 0);
306     if (ri_allowed()) {
307         if (kvm_vm_enable_cap(s, KVM_CAP_S390_RI, 0) == 0) {
308             cap_ri = 1;
309         }
310     }
311     if (gs_allowed()) {
312         if (kvm_vm_enable_cap(s, KVM_CAP_S390_GS, 0) == 0) {
313             cap_gs = 1;
314         }
315     }
316 
317     /*
318      * The migration interface for ais was introduced with kernel 4.13
319      * but the capability itself had been active since 4.12. As migration
320      * support is considered necessary let's disable ais in the 2.10
321      * machine.
322      */
323     /* kvm_vm_enable_cap(s, KVM_CAP_S390_AIS, 0); */
324 
325     qemu_mutex_init(&qemu_sigp_mutex);
326 
327     return 0;
328 }
329 
330 int kvm_arch_irqchip_create(MachineState *ms, KVMState *s)
331 {
332     return 0;
333 }
334 
335 unsigned long kvm_arch_vcpu_id(CPUState *cpu)
336 {
337     return cpu->cpu_index;
338 }
339 
340 int kvm_arch_init_vcpu(CPUState *cs)
341 {
342     S390CPU *cpu = S390_CPU(cs);
343     kvm_s390_set_cpu_state(cpu, cpu->env.cpu_state);
344     cpu->irqstate = g_malloc0(VCPU_IRQ_BUF_SIZE);
345     return 0;
346 }
347 
348 void kvm_s390_reset_vcpu(S390CPU *cpu)
349 {
350     CPUState *cs = CPU(cpu);
351 
352     /* The initial reset call is needed here to reset in-kernel
353      * vcpu data that we can't access directly from QEMU
354      * (i.e. with older kernels which don't support sync_regs/ONE_REG).
355      * Before this ioctl cpu_synchronize_state() is called in common kvm
356      * code (kvm-all) */
357     if (kvm_vcpu_ioctl(cs, KVM_S390_INITIAL_RESET, NULL)) {
358         error_report("Initial CPU reset failed on CPU %i", cs->cpu_index);
359     }
360 }
361 
362 static int can_sync_regs(CPUState *cs, int regs)
363 {
364     return cap_sync_regs && (cs->kvm_run->kvm_valid_regs & regs) == regs;
365 }
366 
367 int kvm_arch_put_registers(CPUState *cs, int level)
368 {
369     S390CPU *cpu = S390_CPU(cs);
370     CPUS390XState *env = &cpu->env;
371     struct kvm_sregs sregs;
372     struct kvm_regs regs;
373     struct kvm_fpu fpu = {};
374     int r;
375     int i;
376 
377     /* always save the PSW  and the GPRS*/
378     cs->kvm_run->psw_addr = env->psw.addr;
379     cs->kvm_run->psw_mask = env->psw.mask;
380 
381     if (can_sync_regs(cs, KVM_SYNC_GPRS)) {
382         for (i = 0; i < 16; i++) {
383             cs->kvm_run->s.regs.gprs[i] = env->regs[i];
384             cs->kvm_run->kvm_dirty_regs |= KVM_SYNC_GPRS;
385         }
386     } else {
387         for (i = 0; i < 16; i++) {
388             regs.gprs[i] = env->regs[i];
389         }
390         r = kvm_vcpu_ioctl(cs, KVM_SET_REGS, &regs);
391         if (r < 0) {
392             return r;
393         }
394     }
395 
396     if (can_sync_regs(cs, KVM_SYNC_VRS)) {
397         for (i = 0; i < 32; i++) {
398             cs->kvm_run->s.regs.vrs[i][0] = env->vregs[i][0].ll;
399             cs->kvm_run->s.regs.vrs[i][1] = env->vregs[i][1].ll;
400         }
401         cs->kvm_run->s.regs.fpc = env->fpc;
402         cs->kvm_run->kvm_dirty_regs |= KVM_SYNC_VRS;
403     } else if (can_sync_regs(cs, KVM_SYNC_FPRS)) {
404         for (i = 0; i < 16; i++) {
405             cs->kvm_run->s.regs.fprs[i] = get_freg(env, i)->ll;
406         }
407         cs->kvm_run->s.regs.fpc = env->fpc;
408         cs->kvm_run->kvm_dirty_regs |= KVM_SYNC_FPRS;
409     } else {
410         /* Floating point */
411         for (i = 0; i < 16; i++) {
412             fpu.fprs[i] = get_freg(env, i)->ll;
413         }
414         fpu.fpc = env->fpc;
415 
416         r = kvm_vcpu_ioctl(cs, KVM_SET_FPU, &fpu);
417         if (r < 0) {
418             return r;
419         }
420     }
421 
422     /* Do we need to save more than that? */
423     if (level == KVM_PUT_RUNTIME_STATE) {
424         return 0;
425     }
426 
427     if (can_sync_regs(cs, KVM_SYNC_ARCH0)) {
428         cs->kvm_run->s.regs.cputm = env->cputm;
429         cs->kvm_run->s.regs.ckc = env->ckc;
430         cs->kvm_run->s.regs.todpr = env->todpr;
431         cs->kvm_run->s.regs.gbea = env->gbea;
432         cs->kvm_run->s.regs.pp = env->pp;
433         cs->kvm_run->kvm_dirty_regs |= KVM_SYNC_ARCH0;
434     } else {
435         /*
436          * These ONE_REGS are not protected by a capability. As they are only
437          * necessary for migration we just trace a possible error, but don't
438          * return with an error return code.
439          */
440         kvm_set_one_reg(cs, KVM_REG_S390_CPU_TIMER, &env->cputm);
441         kvm_set_one_reg(cs, KVM_REG_S390_CLOCK_COMP, &env->ckc);
442         kvm_set_one_reg(cs, KVM_REG_S390_TODPR, &env->todpr);
443         kvm_set_one_reg(cs, KVM_REG_S390_GBEA, &env->gbea);
444         kvm_set_one_reg(cs, KVM_REG_S390_PP, &env->pp);
445     }
446 
447     if (can_sync_regs(cs, KVM_SYNC_RICCB)) {
448         memcpy(cs->kvm_run->s.regs.riccb, env->riccb, 64);
449         cs->kvm_run->kvm_dirty_regs |= KVM_SYNC_RICCB;
450     }
451 
452     /* pfault parameters */
453     if (can_sync_regs(cs, KVM_SYNC_PFAULT)) {
454         cs->kvm_run->s.regs.pft = env->pfault_token;
455         cs->kvm_run->s.regs.pfs = env->pfault_select;
456         cs->kvm_run->s.regs.pfc = env->pfault_compare;
457         cs->kvm_run->kvm_dirty_regs |= KVM_SYNC_PFAULT;
458     } else if (cap_async_pf) {
459         r = kvm_set_one_reg(cs, KVM_REG_S390_PFTOKEN, &env->pfault_token);
460         if (r < 0) {
461             return r;
462         }
463         r = kvm_set_one_reg(cs, KVM_REG_S390_PFCOMPARE, &env->pfault_compare);
464         if (r < 0) {
465             return r;
466         }
467         r = kvm_set_one_reg(cs, KVM_REG_S390_PFSELECT, &env->pfault_select);
468         if (r < 0) {
469             return r;
470         }
471     }
472 
473     /* access registers and control registers*/
474     if (can_sync_regs(cs, KVM_SYNC_ACRS | KVM_SYNC_CRS)) {
475         for (i = 0; i < 16; i++) {
476             cs->kvm_run->s.regs.acrs[i] = env->aregs[i];
477             cs->kvm_run->s.regs.crs[i] = env->cregs[i];
478         }
479         cs->kvm_run->kvm_dirty_regs |= KVM_SYNC_ACRS;
480         cs->kvm_run->kvm_dirty_regs |= KVM_SYNC_CRS;
481     } else {
482         for (i = 0; i < 16; i++) {
483             sregs.acrs[i] = env->aregs[i];
484             sregs.crs[i] = env->cregs[i];
485         }
486         r = kvm_vcpu_ioctl(cs, KVM_SET_SREGS, &sregs);
487         if (r < 0) {
488             return r;
489         }
490     }
491 
492     if (can_sync_regs(cs, KVM_SYNC_GSCB)) {
493         memcpy(cs->kvm_run->s.regs.gscb, env->gscb, 32);
494         cs->kvm_run->kvm_dirty_regs |= KVM_SYNC_GSCB;
495     }
496 
497     /* Finally the prefix */
498     if (can_sync_regs(cs, KVM_SYNC_PREFIX)) {
499         cs->kvm_run->s.regs.prefix = env->psa;
500         cs->kvm_run->kvm_dirty_regs |= KVM_SYNC_PREFIX;
501     } else {
502         /* prefix is only supported via sync regs */
503     }
504     return 0;
505 }
506 
507 int kvm_arch_get_registers(CPUState *cs)
508 {
509     S390CPU *cpu = S390_CPU(cs);
510     CPUS390XState *env = &cpu->env;
511     struct kvm_sregs sregs;
512     struct kvm_regs regs;
513     struct kvm_fpu fpu;
514     int i, r;
515 
516     /* get the PSW */
517     env->psw.addr = cs->kvm_run->psw_addr;
518     env->psw.mask = cs->kvm_run->psw_mask;
519 
520     /* the GPRS */
521     if (can_sync_regs(cs, KVM_SYNC_GPRS)) {
522         for (i = 0; i < 16; i++) {
523             env->regs[i] = cs->kvm_run->s.regs.gprs[i];
524         }
525     } else {
526         r = kvm_vcpu_ioctl(cs, KVM_GET_REGS, &regs);
527         if (r < 0) {
528             return r;
529         }
530          for (i = 0; i < 16; i++) {
531             env->regs[i] = regs.gprs[i];
532         }
533     }
534 
535     /* The ACRS and CRS */
536     if (can_sync_regs(cs, KVM_SYNC_ACRS | KVM_SYNC_CRS)) {
537         for (i = 0; i < 16; i++) {
538             env->aregs[i] = cs->kvm_run->s.regs.acrs[i];
539             env->cregs[i] = cs->kvm_run->s.regs.crs[i];
540         }
541     } else {
542         r = kvm_vcpu_ioctl(cs, KVM_GET_SREGS, &sregs);
543         if (r < 0) {
544             return r;
545         }
546          for (i = 0; i < 16; i++) {
547             env->aregs[i] = sregs.acrs[i];
548             env->cregs[i] = sregs.crs[i];
549         }
550     }
551 
552     /* Floating point and vector registers */
553     if (can_sync_regs(cs, KVM_SYNC_VRS)) {
554         for (i = 0; i < 32; i++) {
555             env->vregs[i][0].ll = cs->kvm_run->s.regs.vrs[i][0];
556             env->vregs[i][1].ll = cs->kvm_run->s.regs.vrs[i][1];
557         }
558         env->fpc = cs->kvm_run->s.regs.fpc;
559     } else if (can_sync_regs(cs, KVM_SYNC_FPRS)) {
560         for (i = 0; i < 16; i++) {
561             get_freg(env, i)->ll = cs->kvm_run->s.regs.fprs[i];
562         }
563         env->fpc = cs->kvm_run->s.regs.fpc;
564     } else {
565         r = kvm_vcpu_ioctl(cs, KVM_GET_FPU, &fpu);
566         if (r < 0) {
567             return r;
568         }
569         for (i = 0; i < 16; i++) {
570             get_freg(env, i)->ll = fpu.fprs[i];
571         }
572         env->fpc = fpu.fpc;
573     }
574 
575     /* The prefix */
576     if (can_sync_regs(cs, KVM_SYNC_PREFIX)) {
577         env->psa = cs->kvm_run->s.regs.prefix;
578     }
579 
580     if (can_sync_regs(cs, KVM_SYNC_ARCH0)) {
581         env->cputm = cs->kvm_run->s.regs.cputm;
582         env->ckc = cs->kvm_run->s.regs.ckc;
583         env->todpr = cs->kvm_run->s.regs.todpr;
584         env->gbea = cs->kvm_run->s.regs.gbea;
585         env->pp = cs->kvm_run->s.regs.pp;
586     } else {
587         /*
588          * These ONE_REGS are not protected by a capability. As they are only
589          * necessary for migration we just trace a possible error, but don't
590          * return with an error return code.
591          */
592         kvm_get_one_reg(cs, KVM_REG_S390_CPU_TIMER, &env->cputm);
593         kvm_get_one_reg(cs, KVM_REG_S390_CLOCK_COMP, &env->ckc);
594         kvm_get_one_reg(cs, KVM_REG_S390_TODPR, &env->todpr);
595         kvm_get_one_reg(cs, KVM_REG_S390_GBEA, &env->gbea);
596         kvm_get_one_reg(cs, KVM_REG_S390_PP, &env->pp);
597     }
598 
599     if (can_sync_regs(cs, KVM_SYNC_RICCB)) {
600         memcpy(env->riccb, cs->kvm_run->s.regs.riccb, 64);
601     }
602 
603     if (can_sync_regs(cs, KVM_SYNC_GSCB)) {
604         memcpy(env->gscb, cs->kvm_run->s.regs.gscb, 32);
605     }
606 
607     /* pfault parameters */
608     if (can_sync_regs(cs, KVM_SYNC_PFAULT)) {
609         env->pfault_token = cs->kvm_run->s.regs.pft;
610         env->pfault_select = cs->kvm_run->s.regs.pfs;
611         env->pfault_compare = cs->kvm_run->s.regs.pfc;
612     } else if (cap_async_pf) {
613         r = kvm_get_one_reg(cs, KVM_REG_S390_PFTOKEN, &env->pfault_token);
614         if (r < 0) {
615             return r;
616         }
617         r = kvm_get_one_reg(cs, KVM_REG_S390_PFCOMPARE, &env->pfault_compare);
618         if (r < 0) {
619             return r;
620         }
621         r = kvm_get_one_reg(cs, KVM_REG_S390_PFSELECT, &env->pfault_select);
622         if (r < 0) {
623             return r;
624         }
625     }
626 
627     return 0;
628 }
629 
630 int kvm_s390_get_clock(uint8_t *tod_high, uint64_t *tod_low)
631 {
632     int r;
633     struct kvm_device_attr attr = {
634         .group = KVM_S390_VM_TOD,
635         .attr = KVM_S390_VM_TOD_LOW,
636         .addr = (uint64_t)tod_low,
637     };
638 
639     r = kvm_vm_ioctl(kvm_state, KVM_GET_DEVICE_ATTR, &attr);
640     if (r) {
641         return r;
642     }
643 
644     attr.attr = KVM_S390_VM_TOD_HIGH;
645     attr.addr = (uint64_t)tod_high;
646     return kvm_vm_ioctl(kvm_state, KVM_GET_DEVICE_ATTR, &attr);
647 }
648 
649 int kvm_s390_get_clock_ext(uint8_t *tod_high, uint64_t *tod_low)
650 {
651     int r;
652     struct kvm_s390_vm_tod_clock gtod;
653     struct kvm_device_attr attr = {
654         .group = KVM_S390_VM_TOD,
655         .attr = KVM_S390_VM_TOD_EXT,
656         .addr = (uint64_t)&gtod,
657     };
658 
659     r = kvm_vm_ioctl(kvm_state, KVM_GET_DEVICE_ATTR, &attr);
660     *tod_high = gtod.epoch_idx;
661     *tod_low  = gtod.tod;
662 
663     return r;
664 }
665 
666 int kvm_s390_set_clock(uint8_t *tod_high, uint64_t *tod_low)
667 {
668     int r;
669     struct kvm_device_attr attr = {
670         .group = KVM_S390_VM_TOD,
671         .attr = KVM_S390_VM_TOD_LOW,
672         .addr = (uint64_t)tod_low,
673     };
674 
675     r = kvm_vm_ioctl(kvm_state, KVM_SET_DEVICE_ATTR, &attr);
676     if (r) {
677         return r;
678     }
679 
680     attr.attr = KVM_S390_VM_TOD_HIGH;
681     attr.addr = (uint64_t)tod_high;
682     return kvm_vm_ioctl(kvm_state, KVM_SET_DEVICE_ATTR, &attr);
683 }
684 
685 int kvm_s390_set_clock_ext(uint8_t *tod_high, uint64_t *tod_low)
686 {
687     struct kvm_s390_vm_tod_clock gtod = {
688         .epoch_idx = *tod_high,
689         .tod  = *tod_low,
690     };
691     struct kvm_device_attr attr = {
692         .group = KVM_S390_VM_TOD,
693         .attr = KVM_S390_VM_TOD_EXT,
694         .addr = (uint64_t)&gtod,
695     };
696 
697     return kvm_vm_ioctl(kvm_state, KVM_SET_DEVICE_ATTR, &attr);
698 }
699 
700 /**
701  * kvm_s390_mem_op:
702  * @addr:      the logical start address in guest memory
703  * @ar:        the access register number
704  * @hostbuf:   buffer in host memory. NULL = do only checks w/o copying
705  * @len:       length that should be transferred
706  * @is_write:  true = write, false = read
707  * Returns:    0 on success, non-zero if an exception or error occurred
708  *
709  * Use KVM ioctl to read/write from/to guest memory. An access exception
710  * is injected into the vCPU in case of translation errors.
711  */
712 int kvm_s390_mem_op(S390CPU *cpu, vaddr addr, uint8_t ar, void *hostbuf,
713                     int len, bool is_write)
714 {
715     struct kvm_s390_mem_op mem_op = {
716         .gaddr = addr,
717         .flags = KVM_S390_MEMOP_F_INJECT_EXCEPTION,
718         .size = len,
719         .op = is_write ? KVM_S390_MEMOP_LOGICAL_WRITE
720                        : KVM_S390_MEMOP_LOGICAL_READ,
721         .buf = (uint64_t)hostbuf,
722         .ar = ar,
723     };
724     int ret;
725 
726     if (!cap_mem_op) {
727         return -ENOSYS;
728     }
729     if (!hostbuf) {
730         mem_op.flags |= KVM_S390_MEMOP_F_CHECK_ONLY;
731     }
732 
733     ret = kvm_vcpu_ioctl(CPU(cpu), KVM_S390_MEM_OP, &mem_op);
734     if (ret < 0) {
735         error_printf("KVM_S390_MEM_OP failed: %s\n", strerror(-ret));
736     }
737     return ret;
738 }
739 
740 /*
741  * Legacy layout for s390:
742  * Older S390 KVM requires the topmost vma of the RAM to be
743  * smaller than an system defined value, which is at least 256GB.
744  * Larger systems have larger values. We put the guest between
745  * the end of data segment (system break) and this value. We
746  * use 32GB as a base to have enough room for the system break
747  * to grow. We also have to use MAP parameters that avoid
748  * read-only mapping of guest pages.
749  */
750 static void *legacy_s390_alloc(size_t size, uint64_t *align)
751 {
752     void *mem;
753 
754     mem = mmap((void *) 0x800000000ULL, size,
755                PROT_EXEC|PROT_READ|PROT_WRITE,
756                MAP_SHARED | MAP_ANONYMOUS | MAP_FIXED, -1, 0);
757     return mem == MAP_FAILED ? NULL : mem;
758 }
759 
760 static uint8_t const *sw_bp_inst;
761 static uint8_t sw_bp_ilen;
762 
763 static void determine_sw_breakpoint_instr(void)
764 {
765         /* DIAG 501 is used for sw breakpoints with old kernels */
766         static const uint8_t diag_501[] = {0x83, 0x24, 0x05, 0x01};
767         /* Instruction 0x0000 is used for sw breakpoints with recent kernels */
768         static const uint8_t instr_0x0000[] = {0x00, 0x00};
769 
770         if (sw_bp_inst) {
771             return;
772         }
773         if (kvm_vm_enable_cap(kvm_state, KVM_CAP_S390_USER_INSTR0, 0)) {
774             sw_bp_inst = diag_501;
775             sw_bp_ilen = sizeof(diag_501);
776             DPRINTF("KVM: will use 4-byte sw breakpoints.\n");
777         } else {
778             sw_bp_inst = instr_0x0000;
779             sw_bp_ilen = sizeof(instr_0x0000);
780             DPRINTF("KVM: will use 2-byte sw breakpoints.\n");
781         }
782 }
783 
784 int kvm_arch_insert_sw_breakpoint(CPUState *cs, struct kvm_sw_breakpoint *bp)
785 {
786     determine_sw_breakpoint_instr();
787 
788     if (cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&bp->saved_insn,
789                             sw_bp_ilen, 0) ||
790         cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)sw_bp_inst, sw_bp_ilen, 1)) {
791         return -EINVAL;
792     }
793     return 0;
794 }
795 
796 int kvm_arch_remove_sw_breakpoint(CPUState *cs, struct kvm_sw_breakpoint *bp)
797 {
798     uint8_t t[MAX_ILEN];
799 
800     if (cpu_memory_rw_debug(cs, bp->pc, t, sw_bp_ilen, 0)) {
801         return -EINVAL;
802     } else if (memcmp(t, sw_bp_inst, sw_bp_ilen)) {
803         return -EINVAL;
804     } else if (cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&bp->saved_insn,
805                                    sw_bp_ilen, 1)) {
806         return -EINVAL;
807     }
808 
809     return 0;
810 }
811 
812 static struct kvm_hw_breakpoint *find_hw_breakpoint(target_ulong addr,
813                                                     int len, int type)
814 {
815     int n;
816 
817     for (n = 0; n < nb_hw_breakpoints; n++) {
818         if (hw_breakpoints[n].addr == addr && hw_breakpoints[n].type == type &&
819             (hw_breakpoints[n].len == len || len == -1)) {
820             return &hw_breakpoints[n];
821         }
822     }
823 
824     return NULL;
825 }
826 
827 static int insert_hw_breakpoint(target_ulong addr, int len, int type)
828 {
829     int size;
830 
831     if (find_hw_breakpoint(addr, len, type)) {
832         return -EEXIST;
833     }
834 
835     size = (nb_hw_breakpoints + 1) * sizeof(struct kvm_hw_breakpoint);
836 
837     if (!hw_breakpoints) {
838         nb_hw_breakpoints = 0;
839         hw_breakpoints = (struct kvm_hw_breakpoint *)g_try_malloc(size);
840     } else {
841         hw_breakpoints =
842             (struct kvm_hw_breakpoint *)g_try_realloc(hw_breakpoints, size);
843     }
844 
845     if (!hw_breakpoints) {
846         nb_hw_breakpoints = 0;
847         return -ENOMEM;
848     }
849 
850     hw_breakpoints[nb_hw_breakpoints].addr = addr;
851     hw_breakpoints[nb_hw_breakpoints].len = len;
852     hw_breakpoints[nb_hw_breakpoints].type = type;
853 
854     nb_hw_breakpoints++;
855 
856     return 0;
857 }
858 
859 int kvm_arch_insert_hw_breakpoint(target_ulong addr,
860                                   target_ulong len, int type)
861 {
862     switch (type) {
863     case GDB_BREAKPOINT_HW:
864         type = KVM_HW_BP;
865         break;
866     case GDB_WATCHPOINT_WRITE:
867         if (len < 1) {
868             return -EINVAL;
869         }
870         type = KVM_HW_WP_WRITE;
871         break;
872     default:
873         return -ENOSYS;
874     }
875     return insert_hw_breakpoint(addr, len, type);
876 }
877 
878 int kvm_arch_remove_hw_breakpoint(target_ulong addr,
879                                   target_ulong len, int type)
880 {
881     int size;
882     struct kvm_hw_breakpoint *bp = find_hw_breakpoint(addr, len, type);
883 
884     if (bp == NULL) {
885         return -ENOENT;
886     }
887 
888     nb_hw_breakpoints--;
889     if (nb_hw_breakpoints > 0) {
890         /*
891          * In order to trim the array, move the last element to the position to
892          * be removed - if necessary.
893          */
894         if (bp != &hw_breakpoints[nb_hw_breakpoints]) {
895             *bp = hw_breakpoints[nb_hw_breakpoints];
896         }
897         size = nb_hw_breakpoints * sizeof(struct kvm_hw_breakpoint);
898         hw_breakpoints =
899              (struct kvm_hw_breakpoint *)g_realloc(hw_breakpoints, size);
900     } else {
901         g_free(hw_breakpoints);
902         hw_breakpoints = NULL;
903     }
904 
905     return 0;
906 }
907 
908 void kvm_arch_remove_all_hw_breakpoints(void)
909 {
910     nb_hw_breakpoints = 0;
911     g_free(hw_breakpoints);
912     hw_breakpoints = NULL;
913 }
914 
915 void kvm_arch_update_guest_debug(CPUState *cpu, struct kvm_guest_debug *dbg)
916 {
917     int i;
918 
919     if (nb_hw_breakpoints > 0) {
920         dbg->arch.nr_hw_bp = nb_hw_breakpoints;
921         dbg->arch.hw_bp = hw_breakpoints;
922 
923         for (i = 0; i < nb_hw_breakpoints; ++i) {
924             hw_breakpoints[i].phys_addr = s390_cpu_get_phys_addr_debug(cpu,
925                                                        hw_breakpoints[i].addr);
926         }
927         dbg->control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_HW_BP;
928     } else {
929         dbg->arch.nr_hw_bp = 0;
930         dbg->arch.hw_bp = NULL;
931     }
932 }
933 
934 void kvm_arch_pre_run(CPUState *cpu, struct kvm_run *run)
935 {
936 }
937 
938 MemTxAttrs kvm_arch_post_run(CPUState *cs, struct kvm_run *run)
939 {
940     return MEMTXATTRS_UNSPECIFIED;
941 }
942 
943 int kvm_arch_process_async_events(CPUState *cs)
944 {
945     return cs->halted;
946 }
947 
948 static int s390_kvm_irq_to_interrupt(struct kvm_s390_irq *irq,
949                                      struct kvm_s390_interrupt *interrupt)
950 {
951     int r = 0;
952 
953     interrupt->type = irq->type;
954     switch (irq->type) {
955     case KVM_S390_INT_VIRTIO:
956         interrupt->parm = irq->u.ext.ext_params;
957         /* fall through */
958     case KVM_S390_INT_PFAULT_INIT:
959     case KVM_S390_INT_PFAULT_DONE:
960         interrupt->parm64 = irq->u.ext.ext_params2;
961         break;
962     case KVM_S390_PROGRAM_INT:
963         interrupt->parm = irq->u.pgm.code;
964         break;
965     case KVM_S390_SIGP_SET_PREFIX:
966         interrupt->parm = irq->u.prefix.address;
967         break;
968     case KVM_S390_INT_SERVICE:
969         interrupt->parm = irq->u.ext.ext_params;
970         break;
971     case KVM_S390_MCHK:
972         interrupt->parm = irq->u.mchk.cr14;
973         interrupt->parm64 = irq->u.mchk.mcic;
974         break;
975     case KVM_S390_INT_EXTERNAL_CALL:
976         interrupt->parm = irq->u.extcall.code;
977         break;
978     case KVM_S390_INT_EMERGENCY:
979         interrupt->parm = irq->u.emerg.code;
980         break;
981     case KVM_S390_SIGP_STOP:
982     case KVM_S390_RESTART:
983         break; /* These types have no parameters */
984     case KVM_S390_INT_IO_MIN...KVM_S390_INT_IO_MAX:
985         interrupt->parm = irq->u.io.subchannel_id << 16;
986         interrupt->parm |= irq->u.io.subchannel_nr;
987         interrupt->parm64 = (uint64_t)irq->u.io.io_int_parm << 32;
988         interrupt->parm64 |= irq->u.io.io_int_word;
989         break;
990     default:
991         r = -EINVAL;
992         break;
993     }
994     return r;
995 }
996 
997 static void inject_vcpu_irq_legacy(CPUState *cs, struct kvm_s390_irq *irq)
998 {
999     struct kvm_s390_interrupt kvmint = {};
1000     int r;
1001 
1002     r = s390_kvm_irq_to_interrupt(irq, &kvmint);
1003     if (r < 0) {
1004         fprintf(stderr, "%s called with bogus interrupt\n", __func__);
1005         exit(1);
1006     }
1007 
1008     r = kvm_vcpu_ioctl(cs, KVM_S390_INTERRUPT, &kvmint);
1009     if (r < 0) {
1010         fprintf(stderr, "KVM failed to inject interrupt\n");
1011         exit(1);
1012     }
1013 }
1014 
1015 void kvm_s390_vcpu_interrupt(S390CPU *cpu, struct kvm_s390_irq *irq)
1016 {
1017     CPUState *cs = CPU(cpu);
1018     int r;
1019 
1020     if (cap_s390_irq) {
1021         r = kvm_vcpu_ioctl(cs, KVM_S390_IRQ, irq);
1022         if (!r) {
1023             return;
1024         }
1025         error_report("KVM failed to inject interrupt %llx", irq->type);
1026         exit(1);
1027     }
1028 
1029     inject_vcpu_irq_legacy(cs, irq);
1030 }
1031 
1032 static void __kvm_s390_floating_interrupt(struct kvm_s390_irq *irq)
1033 {
1034     struct kvm_s390_interrupt kvmint = {};
1035     int r;
1036 
1037     r = s390_kvm_irq_to_interrupt(irq, &kvmint);
1038     if (r < 0) {
1039         fprintf(stderr, "%s called with bogus interrupt\n", __func__);
1040         exit(1);
1041     }
1042 
1043     r = kvm_vm_ioctl(kvm_state, KVM_S390_INTERRUPT, &kvmint);
1044     if (r < 0) {
1045         fprintf(stderr, "KVM failed to inject interrupt\n");
1046         exit(1);
1047     }
1048 }
1049 
1050 void kvm_s390_floating_interrupt(struct kvm_s390_irq *irq)
1051 {
1052     static bool use_flic = true;
1053     int r;
1054 
1055     if (use_flic) {
1056         r = kvm_s390_inject_flic(irq);
1057         if (r == -ENOSYS) {
1058             use_flic = false;
1059         }
1060         if (!r) {
1061             return;
1062         }
1063     }
1064     __kvm_s390_floating_interrupt(irq);
1065 }
1066 
1067 void kvm_s390_service_interrupt(uint32_t parm)
1068 {
1069     struct kvm_s390_irq irq = {
1070         .type = KVM_S390_INT_SERVICE,
1071         .u.ext.ext_params = parm,
1072     };
1073 
1074     kvm_s390_floating_interrupt(&irq);
1075 }
1076 
1077 void kvm_s390_program_interrupt(S390CPU *cpu, uint16_t code)
1078 {
1079     struct kvm_s390_irq irq = {
1080         .type = KVM_S390_PROGRAM_INT,
1081         .u.pgm.code = code,
1082     };
1083 
1084     kvm_s390_vcpu_interrupt(cpu, &irq);
1085 }
1086 
1087 void kvm_s390_access_exception(S390CPU *cpu, uint16_t code, uint64_t te_code)
1088 {
1089     struct kvm_s390_irq irq = {
1090         .type = KVM_S390_PROGRAM_INT,
1091         .u.pgm.code = code,
1092         .u.pgm.trans_exc_code = te_code,
1093         .u.pgm.exc_access_id = te_code & 3,
1094     };
1095 
1096     kvm_s390_vcpu_interrupt(cpu, &irq);
1097 }
1098 
1099 static int kvm_sclp_service_call(S390CPU *cpu, struct kvm_run *run,
1100                                  uint16_t ipbh0)
1101 {
1102     CPUS390XState *env = &cpu->env;
1103     uint64_t sccb;
1104     uint32_t code;
1105     int r = 0;
1106 
1107     cpu_synchronize_state(CPU(cpu));
1108     sccb = env->regs[ipbh0 & 0xf];
1109     code = env->regs[(ipbh0 & 0xf0) >> 4];
1110 
1111     r = sclp_service_call(env, sccb, code);
1112     if (r < 0) {
1113         kvm_s390_program_interrupt(cpu, -r);
1114     } else {
1115         setcc(cpu, r);
1116     }
1117 
1118     return 0;
1119 }
1120 
1121 static int handle_b2(S390CPU *cpu, struct kvm_run *run, uint8_t ipa1)
1122 {
1123     CPUS390XState *env = &cpu->env;
1124     int rc = 0;
1125     uint16_t ipbh0 = (run->s390_sieic.ipb & 0xffff0000) >> 16;
1126 
1127     cpu_synchronize_state(CPU(cpu));
1128 
1129     switch (ipa1) {
1130     case PRIV_B2_XSCH:
1131         ioinst_handle_xsch(cpu, env->regs[1]);
1132         break;
1133     case PRIV_B2_CSCH:
1134         ioinst_handle_csch(cpu, env->regs[1]);
1135         break;
1136     case PRIV_B2_HSCH:
1137         ioinst_handle_hsch(cpu, env->regs[1]);
1138         break;
1139     case PRIV_B2_MSCH:
1140         ioinst_handle_msch(cpu, env->regs[1], run->s390_sieic.ipb);
1141         break;
1142     case PRIV_B2_SSCH:
1143         ioinst_handle_ssch(cpu, env->regs[1], run->s390_sieic.ipb);
1144         break;
1145     case PRIV_B2_STCRW:
1146         ioinst_handle_stcrw(cpu, run->s390_sieic.ipb);
1147         break;
1148     case PRIV_B2_STSCH:
1149         ioinst_handle_stsch(cpu, env->regs[1], run->s390_sieic.ipb);
1150         break;
1151     case PRIV_B2_TSCH:
1152         /* We should only get tsch via KVM_EXIT_S390_TSCH. */
1153         fprintf(stderr, "Spurious tsch intercept\n");
1154         break;
1155     case PRIV_B2_CHSC:
1156         ioinst_handle_chsc(cpu, run->s390_sieic.ipb);
1157         break;
1158     case PRIV_B2_TPI:
1159         /* This should have been handled by kvm already. */
1160         fprintf(stderr, "Spurious tpi intercept\n");
1161         break;
1162     case PRIV_B2_SCHM:
1163         ioinst_handle_schm(cpu, env->regs[1], env->regs[2],
1164                            run->s390_sieic.ipb);
1165         break;
1166     case PRIV_B2_RSCH:
1167         ioinst_handle_rsch(cpu, env->regs[1]);
1168         break;
1169     case PRIV_B2_RCHP:
1170         ioinst_handle_rchp(cpu, env->regs[1]);
1171         break;
1172     case PRIV_B2_STCPS:
1173         /* We do not provide this instruction, it is suppressed. */
1174         break;
1175     case PRIV_B2_SAL:
1176         ioinst_handle_sal(cpu, env->regs[1]);
1177         break;
1178     case PRIV_B2_SIGA:
1179         /* Not provided, set CC = 3 for subchannel not operational */
1180         setcc(cpu, 3);
1181         break;
1182     case PRIV_B2_SCLP_CALL:
1183         rc = kvm_sclp_service_call(cpu, run, ipbh0);
1184         break;
1185     default:
1186         rc = -1;
1187         DPRINTF("KVM: unhandled PRIV: 0xb2%x\n", ipa1);
1188         break;
1189     }
1190 
1191     return rc;
1192 }
1193 
1194 static uint64_t get_base_disp_rxy(S390CPU *cpu, struct kvm_run *run,
1195                                   uint8_t *ar)
1196 {
1197     CPUS390XState *env = &cpu->env;
1198     uint32_t x2 = (run->s390_sieic.ipa & 0x000f);
1199     uint32_t base2 = run->s390_sieic.ipb >> 28;
1200     uint32_t disp2 = ((run->s390_sieic.ipb & 0x0fff0000) >> 16) +
1201                      ((run->s390_sieic.ipb & 0xff00) << 4);
1202 
1203     if (disp2 & 0x80000) {
1204         disp2 += 0xfff00000;
1205     }
1206     if (ar) {
1207         *ar = base2;
1208     }
1209 
1210     return (base2 ? env->regs[base2] : 0) +
1211            (x2 ? env->regs[x2] : 0) + (long)(int)disp2;
1212 }
1213 
1214 static uint64_t get_base_disp_rsy(S390CPU *cpu, struct kvm_run *run,
1215                                   uint8_t *ar)
1216 {
1217     CPUS390XState *env = &cpu->env;
1218     uint32_t base2 = run->s390_sieic.ipb >> 28;
1219     uint32_t disp2 = ((run->s390_sieic.ipb & 0x0fff0000) >> 16) +
1220                      ((run->s390_sieic.ipb & 0xff00) << 4);
1221 
1222     if (disp2 & 0x80000) {
1223         disp2 += 0xfff00000;
1224     }
1225     if (ar) {
1226         *ar = base2;
1227     }
1228 
1229     return (base2 ? env->regs[base2] : 0) + (long)(int)disp2;
1230 }
1231 
1232 static int kvm_clp_service_call(S390CPU *cpu, struct kvm_run *run)
1233 {
1234     uint8_t r2 = (run->s390_sieic.ipb & 0x000f0000) >> 16;
1235 
1236     if (s390_has_feat(S390_FEAT_ZPCI)) {
1237         return clp_service_call(cpu, r2);
1238     } else {
1239         return -1;
1240     }
1241 }
1242 
1243 static int kvm_pcilg_service_call(S390CPU *cpu, struct kvm_run *run)
1244 {
1245     uint8_t r1 = (run->s390_sieic.ipb & 0x00f00000) >> 20;
1246     uint8_t r2 = (run->s390_sieic.ipb & 0x000f0000) >> 16;
1247 
1248     if (s390_has_feat(S390_FEAT_ZPCI)) {
1249         return pcilg_service_call(cpu, r1, r2);
1250     } else {
1251         return -1;
1252     }
1253 }
1254 
1255 static int kvm_pcistg_service_call(S390CPU *cpu, struct kvm_run *run)
1256 {
1257     uint8_t r1 = (run->s390_sieic.ipb & 0x00f00000) >> 20;
1258     uint8_t r2 = (run->s390_sieic.ipb & 0x000f0000) >> 16;
1259 
1260     if (s390_has_feat(S390_FEAT_ZPCI)) {
1261         return pcistg_service_call(cpu, r1, r2);
1262     } else {
1263         return -1;
1264     }
1265 }
1266 
1267 static int kvm_stpcifc_service_call(S390CPU *cpu, struct kvm_run *run)
1268 {
1269     uint8_t r1 = (run->s390_sieic.ipa & 0x00f0) >> 4;
1270     uint64_t fiba;
1271     uint8_t ar;
1272 
1273     if (s390_has_feat(S390_FEAT_ZPCI)) {
1274         cpu_synchronize_state(CPU(cpu));
1275         fiba = get_base_disp_rxy(cpu, run, &ar);
1276 
1277         return stpcifc_service_call(cpu, r1, fiba, ar);
1278     } else {
1279         return -1;
1280     }
1281 }
1282 
1283 static int kvm_sic_service_call(S390CPU *cpu, struct kvm_run *run)
1284 {
1285     CPUS390XState *env = &cpu->env;
1286     uint8_t r1 = (run->s390_sieic.ipa & 0x00f0) >> 4;
1287     uint8_t r3 = run->s390_sieic.ipa & 0x000f;
1288     uint8_t isc;
1289     uint16_t mode;
1290     int r;
1291 
1292     cpu_synchronize_state(CPU(cpu));
1293     mode = env->regs[r1] & 0xffff;
1294     isc = (env->regs[r3] >> 27) & 0x7;
1295     r = css_do_sic(env, isc, mode);
1296     if (r) {
1297         kvm_s390_program_interrupt(cpu, -r);
1298     }
1299 
1300     return 0;
1301 }
1302 
1303 static int kvm_rpcit_service_call(S390CPU *cpu, struct kvm_run *run)
1304 {
1305     uint8_t r1 = (run->s390_sieic.ipb & 0x00f00000) >> 20;
1306     uint8_t r2 = (run->s390_sieic.ipb & 0x000f0000) >> 16;
1307 
1308     if (s390_has_feat(S390_FEAT_ZPCI)) {
1309         return rpcit_service_call(cpu, r1, r2);
1310     } else {
1311         return -1;
1312     }
1313 }
1314 
1315 static int kvm_pcistb_service_call(S390CPU *cpu, struct kvm_run *run)
1316 {
1317     uint8_t r1 = (run->s390_sieic.ipa & 0x00f0) >> 4;
1318     uint8_t r3 = run->s390_sieic.ipa & 0x000f;
1319     uint64_t gaddr;
1320     uint8_t ar;
1321 
1322     if (s390_has_feat(S390_FEAT_ZPCI)) {
1323         cpu_synchronize_state(CPU(cpu));
1324         gaddr = get_base_disp_rsy(cpu, run, &ar);
1325 
1326         return pcistb_service_call(cpu, r1, r3, gaddr, ar);
1327     } else {
1328         return -1;
1329     }
1330 }
1331 
1332 static int kvm_mpcifc_service_call(S390CPU *cpu, struct kvm_run *run)
1333 {
1334     uint8_t r1 = (run->s390_sieic.ipa & 0x00f0) >> 4;
1335     uint64_t fiba;
1336     uint8_t ar;
1337 
1338     if (s390_has_feat(S390_FEAT_ZPCI)) {
1339         cpu_synchronize_state(CPU(cpu));
1340         fiba = get_base_disp_rxy(cpu, run, &ar);
1341 
1342         return mpcifc_service_call(cpu, r1, fiba, ar);
1343     } else {
1344         return -1;
1345     }
1346 }
1347 
1348 static int handle_b9(S390CPU *cpu, struct kvm_run *run, uint8_t ipa1)
1349 {
1350     int r = 0;
1351 
1352     switch (ipa1) {
1353     case PRIV_B9_CLP:
1354         r = kvm_clp_service_call(cpu, run);
1355         break;
1356     case PRIV_B9_PCISTG:
1357         r = kvm_pcistg_service_call(cpu, run);
1358         break;
1359     case PRIV_B9_PCILG:
1360         r = kvm_pcilg_service_call(cpu, run);
1361         break;
1362     case PRIV_B9_RPCIT:
1363         r = kvm_rpcit_service_call(cpu, run);
1364         break;
1365     case PRIV_B9_EQBS:
1366         /* just inject exception */
1367         r = -1;
1368         break;
1369     default:
1370         r = -1;
1371         DPRINTF("KVM: unhandled PRIV: 0xb9%x\n", ipa1);
1372         break;
1373     }
1374 
1375     return r;
1376 }
1377 
1378 static int handle_eb(S390CPU *cpu, struct kvm_run *run, uint8_t ipbl)
1379 {
1380     int r = 0;
1381 
1382     switch (ipbl) {
1383     case PRIV_EB_PCISTB:
1384         r = kvm_pcistb_service_call(cpu, run);
1385         break;
1386     case PRIV_EB_SIC:
1387         r = kvm_sic_service_call(cpu, run);
1388         break;
1389     case PRIV_EB_SQBS:
1390         /* just inject exception */
1391         r = -1;
1392         break;
1393     default:
1394         r = -1;
1395         DPRINTF("KVM: unhandled PRIV: 0xeb%x\n", ipbl);
1396         break;
1397     }
1398 
1399     return r;
1400 }
1401 
1402 static int handle_e3(S390CPU *cpu, struct kvm_run *run, uint8_t ipbl)
1403 {
1404     int r = 0;
1405 
1406     switch (ipbl) {
1407     case PRIV_E3_MPCIFC:
1408         r = kvm_mpcifc_service_call(cpu, run);
1409         break;
1410     case PRIV_E3_STPCIFC:
1411         r = kvm_stpcifc_service_call(cpu, run);
1412         break;
1413     default:
1414         r = -1;
1415         DPRINTF("KVM: unhandled PRIV: 0xe3%x\n", ipbl);
1416         break;
1417     }
1418 
1419     return r;
1420 }
1421 
1422 static int handle_hypercall(S390CPU *cpu, struct kvm_run *run)
1423 {
1424     CPUS390XState *env = &cpu->env;
1425     int ret;
1426 
1427     cpu_synchronize_state(CPU(cpu));
1428     ret = s390_virtio_hypercall(env);
1429     if (ret == -EINVAL) {
1430         kvm_s390_program_interrupt(cpu, PGM_SPECIFICATION);
1431         return 0;
1432     }
1433 
1434     return ret;
1435 }
1436 
1437 static void kvm_handle_diag_288(S390CPU *cpu, struct kvm_run *run)
1438 {
1439     uint64_t r1, r3;
1440     int rc;
1441 
1442     cpu_synchronize_state(CPU(cpu));
1443     r1 = (run->s390_sieic.ipa & 0x00f0) >> 4;
1444     r3 = run->s390_sieic.ipa & 0x000f;
1445     rc = handle_diag_288(&cpu->env, r1, r3);
1446     if (rc) {
1447         kvm_s390_program_interrupt(cpu, PGM_SPECIFICATION);
1448     }
1449 }
1450 
1451 static void kvm_handle_diag_308(S390CPU *cpu, struct kvm_run *run)
1452 {
1453     uint64_t r1, r3;
1454 
1455     cpu_synchronize_state(CPU(cpu));
1456     r1 = (run->s390_sieic.ipa & 0x00f0) >> 4;
1457     r3 = run->s390_sieic.ipa & 0x000f;
1458     handle_diag_308(&cpu->env, r1, r3);
1459 }
1460 
1461 static int handle_sw_breakpoint(S390CPU *cpu, struct kvm_run *run)
1462 {
1463     CPUS390XState *env = &cpu->env;
1464     unsigned long pc;
1465 
1466     cpu_synchronize_state(CPU(cpu));
1467 
1468     pc = env->psw.addr - sw_bp_ilen;
1469     if (kvm_find_sw_breakpoint(CPU(cpu), pc)) {
1470         env->psw.addr = pc;
1471         return EXCP_DEBUG;
1472     }
1473 
1474     return -ENOENT;
1475 }
1476 
1477 #define DIAG_KVM_CODE_MASK 0x000000000000ffff
1478 
1479 static int handle_diag(S390CPU *cpu, struct kvm_run *run, uint32_t ipb)
1480 {
1481     int r = 0;
1482     uint16_t func_code;
1483 
1484     /*
1485      * For any diagnose call we support, bits 48-63 of the resulting
1486      * address specify the function code; the remainder is ignored.
1487      */
1488     func_code = decode_basedisp_rs(&cpu->env, ipb, NULL) & DIAG_KVM_CODE_MASK;
1489     switch (func_code) {
1490     case DIAG_TIMEREVENT:
1491         kvm_handle_diag_288(cpu, run);
1492         break;
1493     case DIAG_IPL:
1494         kvm_handle_diag_308(cpu, run);
1495         break;
1496     case DIAG_KVM_HYPERCALL:
1497         r = handle_hypercall(cpu, run);
1498         break;
1499     case DIAG_KVM_BREAKPOINT:
1500         r = handle_sw_breakpoint(cpu, run);
1501         break;
1502     default:
1503         DPRINTF("KVM: unknown DIAG: 0x%x\n", func_code);
1504         kvm_s390_program_interrupt(cpu, PGM_SPECIFICATION);
1505         break;
1506     }
1507 
1508     return r;
1509 }
1510 
1511 typedef struct SigpInfo {
1512     uint64_t param;
1513     int cc;
1514     uint64_t *status_reg;
1515 } SigpInfo;
1516 
1517 static void set_sigp_status(SigpInfo *si, uint64_t status)
1518 {
1519     *si->status_reg &= 0xffffffff00000000ULL;
1520     *si->status_reg |= status;
1521     si->cc = SIGP_CC_STATUS_STORED;
1522 }
1523 
1524 static void sigp_start(CPUState *cs, run_on_cpu_data arg)
1525 {
1526     S390CPU *cpu = S390_CPU(cs);
1527     SigpInfo *si = arg.host_ptr;
1528 
1529     if (s390_cpu_get_state(cpu) != CPU_STATE_STOPPED) {
1530         si->cc = SIGP_CC_ORDER_CODE_ACCEPTED;
1531         return;
1532     }
1533 
1534     s390_cpu_set_state(CPU_STATE_OPERATING, cpu);
1535     si->cc = SIGP_CC_ORDER_CODE_ACCEPTED;
1536 }
1537 
1538 static void sigp_stop(CPUState *cs, run_on_cpu_data arg)
1539 {
1540     S390CPU *cpu = S390_CPU(cs);
1541     SigpInfo *si = arg.host_ptr;
1542 
1543     if (s390_cpu_get_state(cpu) != CPU_STATE_OPERATING) {
1544         si->cc = SIGP_CC_ORDER_CODE_ACCEPTED;
1545         return;
1546     }
1547 
1548     /* disabled wait - sleeping in user space */
1549     if (cs->halted) {
1550         s390_cpu_set_state(CPU_STATE_STOPPED, cpu);
1551     } else {
1552         /* execute the stop function */
1553         cpu->env.sigp_order = SIGP_STOP;
1554         cpu_inject_stop(cpu);
1555     }
1556     si->cc = SIGP_CC_ORDER_CODE_ACCEPTED;
1557 }
1558 
1559 #define ADTL_GS_OFFSET   1024 /* offset of GS data in adtl save area */
1560 #define ADTL_GS_MIN_SIZE 2048 /* minimal size of adtl save area for GS */
1561 static int do_store_adtl_status(S390CPU *cpu, hwaddr addr, hwaddr len)
1562 {
1563     hwaddr save = len;
1564     void *mem;
1565 
1566     mem = cpu_physical_memory_map(addr, &save, 1);
1567     if (!mem) {
1568         return -EFAULT;
1569     }
1570     if (save != len) {
1571         cpu_physical_memory_unmap(mem, len, 1, 0);
1572         return -EFAULT;
1573     }
1574 
1575     if (s390_has_feat(S390_FEAT_VECTOR)) {
1576         memcpy(mem, &cpu->env.vregs, 512);
1577     }
1578     if (s390_has_feat(S390_FEAT_GUARDED_STORAGE) && len >= ADTL_GS_MIN_SIZE) {
1579         memcpy(mem + ADTL_GS_OFFSET, &cpu->env.gscb, 32);
1580     }
1581 
1582     cpu_physical_memory_unmap(mem, len, 1, len);
1583 
1584     return 0;
1585 }
1586 
1587 static void sigp_stop_and_store_status(CPUState *cs, run_on_cpu_data arg)
1588 {
1589     S390CPU *cpu = S390_CPU(cs);
1590     SigpInfo *si = arg.host_ptr;
1591 
1592     /* disabled wait - sleeping in user space */
1593     if (s390_cpu_get_state(cpu) == CPU_STATE_OPERATING && cs->halted) {
1594         s390_cpu_set_state(CPU_STATE_STOPPED, cpu);
1595     }
1596 
1597     switch (s390_cpu_get_state(cpu)) {
1598     case CPU_STATE_OPERATING:
1599         cpu->env.sigp_order = SIGP_STOP_STORE_STATUS;
1600         cpu_inject_stop(cpu);
1601         /* store will be performed when handling the stop intercept */
1602         break;
1603     case CPU_STATE_STOPPED:
1604         /* already stopped, just store the status */
1605         cpu_synchronize_state(cs);
1606         s390_store_status(cpu, S390_STORE_STATUS_DEF_ADDR, true);
1607         break;
1608     }
1609     si->cc = SIGP_CC_ORDER_CODE_ACCEPTED;
1610 }
1611 
1612 static void sigp_store_status_at_address(CPUState *cs, run_on_cpu_data arg)
1613 {
1614     S390CPU *cpu = S390_CPU(cs);
1615     SigpInfo *si = arg.host_ptr;
1616     uint32_t address = si->param & 0x7ffffe00u;
1617 
1618     /* cpu has to be stopped */
1619     if (s390_cpu_get_state(cpu) != CPU_STATE_STOPPED) {
1620         set_sigp_status(si, SIGP_STAT_INCORRECT_STATE);
1621         return;
1622     }
1623 
1624     cpu_synchronize_state(cs);
1625 
1626     if (s390_store_status(cpu, address, false)) {
1627         set_sigp_status(si, SIGP_STAT_INVALID_PARAMETER);
1628         return;
1629     }
1630     si->cc = SIGP_CC_ORDER_CODE_ACCEPTED;
1631 }
1632 
1633 #define ADTL_SAVE_LC_MASK  0xfUL
1634 static void sigp_store_adtl_status(CPUState *cs, run_on_cpu_data arg)
1635 {
1636     S390CPU *cpu = S390_CPU(cs);
1637     SigpInfo *si = arg.host_ptr;
1638     uint8_t lc = si->param & ADTL_SAVE_LC_MASK;
1639     hwaddr addr = si->param & ~ADTL_SAVE_LC_MASK;
1640     hwaddr len = 1UL << (lc ? lc : 10);
1641 
1642     if (!s390_has_feat(S390_FEAT_VECTOR) &&
1643         !s390_has_feat(S390_FEAT_GUARDED_STORAGE)) {
1644         set_sigp_status(si, SIGP_STAT_INVALID_ORDER);
1645         return;
1646     }
1647 
1648     /* cpu has to be stopped */
1649     if (s390_cpu_get_state(cpu) != CPU_STATE_STOPPED) {
1650         set_sigp_status(si, SIGP_STAT_INCORRECT_STATE);
1651         return;
1652     }
1653 
1654     /* address must be aligned to length */
1655     if (addr & (len - 1)) {
1656         set_sigp_status(si, SIGP_STAT_INVALID_PARAMETER);
1657         return;
1658     }
1659 
1660     /* no GS: only lc == 0 is valid */
1661     if (!s390_has_feat(S390_FEAT_GUARDED_STORAGE) &&
1662         lc != 0) {
1663         set_sigp_status(si, SIGP_STAT_INVALID_PARAMETER);
1664         return;
1665     }
1666 
1667     /* GS: 0, 10, 11, 12 are valid */
1668     if (s390_has_feat(S390_FEAT_GUARDED_STORAGE) &&
1669         lc != 0 &&
1670         lc != 10 &&
1671         lc != 11 &&
1672         lc != 12) {
1673         set_sigp_status(si, SIGP_STAT_INVALID_PARAMETER);
1674         return;
1675     }
1676 
1677     cpu_synchronize_state(cs);
1678 
1679     if (do_store_adtl_status(cpu, addr, len)) {
1680         set_sigp_status(si, SIGP_STAT_INVALID_PARAMETER);
1681         return;
1682     }
1683     si->cc = SIGP_CC_ORDER_CODE_ACCEPTED;
1684 }
1685 
1686 static void sigp_restart(CPUState *cs, run_on_cpu_data arg)
1687 {
1688     S390CPU *cpu = S390_CPU(cs);
1689     SigpInfo *si = arg.host_ptr;
1690 
1691     switch (s390_cpu_get_state(cpu)) {
1692     case CPU_STATE_STOPPED:
1693         /* the restart irq has to be delivered prior to any other pending irq */
1694         cpu_synchronize_state(cs);
1695         do_restart_interrupt(&cpu->env);
1696         s390_cpu_set_state(CPU_STATE_OPERATING, cpu);
1697         break;
1698     case CPU_STATE_OPERATING:
1699         cpu_inject_restart(cpu);
1700         break;
1701     }
1702     si->cc = SIGP_CC_ORDER_CODE_ACCEPTED;
1703 }
1704 
1705 int kvm_s390_cpu_restart(S390CPU *cpu)
1706 {
1707     SigpInfo si = {};
1708 
1709     run_on_cpu(CPU(cpu), sigp_restart, RUN_ON_CPU_HOST_PTR(&si));
1710     DPRINTF("DONE: KVM cpu restart: %p\n", &cpu->env);
1711     return 0;
1712 }
1713 
1714 static void sigp_initial_cpu_reset(CPUState *cs, run_on_cpu_data arg)
1715 {
1716     S390CPU *cpu = S390_CPU(cs);
1717     S390CPUClass *scc = S390_CPU_GET_CLASS(cpu);
1718     SigpInfo *si = arg.host_ptr;
1719 
1720     cpu_synchronize_state(cs);
1721     scc->initial_cpu_reset(cs);
1722     cpu_synchronize_post_reset(cs);
1723     si->cc = SIGP_CC_ORDER_CODE_ACCEPTED;
1724 }
1725 
1726 static void sigp_cpu_reset(CPUState *cs, run_on_cpu_data arg)
1727 {
1728     S390CPU *cpu = S390_CPU(cs);
1729     S390CPUClass *scc = S390_CPU_GET_CLASS(cpu);
1730     SigpInfo *si = arg.host_ptr;
1731 
1732     cpu_synchronize_state(cs);
1733     scc->cpu_reset(cs);
1734     cpu_synchronize_post_reset(cs);
1735     si->cc = SIGP_CC_ORDER_CODE_ACCEPTED;
1736 }
1737 
1738 static void sigp_set_prefix(CPUState *cs, run_on_cpu_data arg)
1739 {
1740     S390CPU *cpu = S390_CPU(cs);
1741     SigpInfo *si = arg.host_ptr;
1742     uint32_t addr = si->param & 0x7fffe000u;
1743 
1744     cpu_synchronize_state(cs);
1745 
1746     if (!address_space_access_valid(&address_space_memory, addr,
1747                                     sizeof(struct LowCore), false)) {
1748         set_sigp_status(si, SIGP_STAT_INVALID_PARAMETER);
1749         return;
1750     }
1751 
1752     /* cpu has to be stopped */
1753     if (s390_cpu_get_state(cpu) != CPU_STATE_STOPPED) {
1754         set_sigp_status(si, SIGP_STAT_INCORRECT_STATE);
1755         return;
1756     }
1757 
1758     cpu->env.psa = addr;
1759     cpu_synchronize_post_init(cs);
1760     si->cc = SIGP_CC_ORDER_CODE_ACCEPTED;
1761 }
1762 
1763 static int handle_sigp_single_dst(S390CPU *dst_cpu, uint8_t order,
1764                                   uint64_t param, uint64_t *status_reg)
1765 {
1766     SigpInfo si = {
1767         .param = param,
1768         .status_reg = status_reg,
1769     };
1770 
1771     /* cpu available? */
1772     if (dst_cpu == NULL) {
1773         return SIGP_CC_NOT_OPERATIONAL;
1774     }
1775 
1776     /* only resets can break pending orders */
1777     if (dst_cpu->env.sigp_order != 0 &&
1778         order != SIGP_CPU_RESET &&
1779         order != SIGP_INITIAL_CPU_RESET) {
1780         return SIGP_CC_BUSY;
1781     }
1782 
1783     switch (order) {
1784     case SIGP_START:
1785         run_on_cpu(CPU(dst_cpu), sigp_start, RUN_ON_CPU_HOST_PTR(&si));
1786         break;
1787     case SIGP_STOP:
1788         run_on_cpu(CPU(dst_cpu), sigp_stop, RUN_ON_CPU_HOST_PTR(&si));
1789         break;
1790     case SIGP_RESTART:
1791         run_on_cpu(CPU(dst_cpu), sigp_restart, RUN_ON_CPU_HOST_PTR(&si));
1792         break;
1793     case SIGP_STOP_STORE_STATUS:
1794         run_on_cpu(CPU(dst_cpu), sigp_stop_and_store_status, RUN_ON_CPU_HOST_PTR(&si));
1795         break;
1796     case SIGP_STORE_STATUS_ADDR:
1797         run_on_cpu(CPU(dst_cpu), sigp_store_status_at_address, RUN_ON_CPU_HOST_PTR(&si));
1798         break;
1799     case SIGP_STORE_ADTL_STATUS:
1800         run_on_cpu(CPU(dst_cpu), sigp_store_adtl_status, RUN_ON_CPU_HOST_PTR(&si));
1801         break;
1802     case SIGP_SET_PREFIX:
1803         run_on_cpu(CPU(dst_cpu), sigp_set_prefix, RUN_ON_CPU_HOST_PTR(&si));
1804         break;
1805     case SIGP_INITIAL_CPU_RESET:
1806         run_on_cpu(CPU(dst_cpu), sigp_initial_cpu_reset, RUN_ON_CPU_HOST_PTR(&si));
1807         break;
1808     case SIGP_CPU_RESET:
1809         run_on_cpu(CPU(dst_cpu), sigp_cpu_reset, RUN_ON_CPU_HOST_PTR(&si));
1810         break;
1811     default:
1812         DPRINTF("KVM: unknown SIGP: 0x%x\n", order);
1813         set_sigp_status(&si, SIGP_STAT_INVALID_ORDER);
1814     }
1815 
1816     return si.cc;
1817 }
1818 
1819 static int sigp_set_architecture(S390CPU *cpu, uint32_t param,
1820                                  uint64_t *status_reg)
1821 {
1822     CPUState *cur_cs;
1823     S390CPU *cur_cpu;
1824     bool all_stopped = true;
1825 
1826     CPU_FOREACH(cur_cs) {
1827         cur_cpu = S390_CPU(cur_cs);
1828 
1829         if (cur_cpu == cpu) {
1830             continue;
1831         }
1832         if (s390_cpu_get_state(cur_cpu) != CPU_STATE_STOPPED) {
1833             all_stopped = false;
1834         }
1835     }
1836 
1837     *status_reg &= 0xffffffff00000000ULL;
1838 
1839     /* Reject set arch order, with czam we're always in z/Arch mode. */
1840     *status_reg |= (all_stopped ? SIGP_STAT_INVALID_PARAMETER :
1841                     SIGP_STAT_INCORRECT_STATE);
1842     return SIGP_CC_STATUS_STORED;
1843 }
1844 
1845 static int handle_sigp(S390CPU *cpu, uint8_t ipa1, uint32_t ipb)
1846 {
1847     CPUS390XState *env = &cpu->env;
1848     const uint8_t r1 = ipa1 >> 4;
1849     const uint8_t r3 = ipa1 & 0x0f;
1850     int ret;
1851     uint8_t order;
1852     uint64_t *status_reg;
1853     uint64_t param;
1854     S390CPU *dst_cpu = NULL;
1855 
1856     cpu_synchronize_state(CPU(cpu));
1857 
1858     /* get order code */
1859     order = decode_basedisp_rs(env, ipb, NULL)
1860         & SIGP_ORDER_MASK;
1861     status_reg = &env->regs[r1];
1862     param = (r1 % 2) ? env->regs[r1] : env->regs[r1 + 1];
1863 
1864     if (qemu_mutex_trylock(&qemu_sigp_mutex)) {
1865         ret = SIGP_CC_BUSY;
1866         goto out;
1867     }
1868 
1869     switch (order) {
1870     case SIGP_SET_ARCH:
1871         ret = sigp_set_architecture(cpu, param, status_reg);
1872         break;
1873     default:
1874         /* all other sigp orders target a single vcpu */
1875         dst_cpu = s390_cpu_addr2state(env->regs[r3]);
1876         ret = handle_sigp_single_dst(dst_cpu, order, param, status_reg);
1877     }
1878     qemu_mutex_unlock(&qemu_sigp_mutex);
1879 
1880 out:
1881     trace_kvm_sigp_finished(order, CPU(cpu)->cpu_index,
1882                             dst_cpu ? CPU(dst_cpu)->cpu_index : -1, ret);
1883 
1884     if (ret >= 0) {
1885         setcc(cpu, ret);
1886         return 0;
1887     }
1888 
1889     return ret;
1890 }
1891 
1892 static int handle_instruction(S390CPU *cpu, struct kvm_run *run)
1893 {
1894     unsigned int ipa0 = (run->s390_sieic.ipa & 0xff00);
1895     uint8_t ipa1 = run->s390_sieic.ipa & 0x00ff;
1896     int r = -1;
1897 
1898     DPRINTF("handle_instruction 0x%x 0x%x\n",
1899             run->s390_sieic.ipa, run->s390_sieic.ipb);
1900     switch (ipa0) {
1901     case IPA0_B2:
1902         r = handle_b2(cpu, run, ipa1);
1903         break;
1904     case IPA0_B9:
1905         r = handle_b9(cpu, run, ipa1);
1906         break;
1907     case IPA0_EB:
1908         r = handle_eb(cpu, run, run->s390_sieic.ipb & 0xff);
1909         break;
1910     case IPA0_E3:
1911         r = handle_e3(cpu, run, run->s390_sieic.ipb & 0xff);
1912         break;
1913     case IPA0_DIAG:
1914         r = handle_diag(cpu, run, run->s390_sieic.ipb);
1915         break;
1916     case IPA0_SIGP:
1917         r = handle_sigp(cpu, ipa1, run->s390_sieic.ipb);
1918         break;
1919     }
1920 
1921     if (r < 0) {
1922         r = 0;
1923         kvm_s390_program_interrupt(cpu, PGM_OPERATION);
1924     }
1925 
1926     return r;
1927 }
1928 
1929 static void unmanageable_intercept(S390CPU *cpu, const char *str, int pswoffset)
1930 {
1931     CPUState *cs = CPU(cpu);
1932 
1933     error_report("Unmanageable %s! CPU%i new PSW: 0x%016lx:%016lx",
1934                  str, cs->cpu_index, ldq_phys(cs->as, cpu->env.psa + pswoffset),
1935                  ldq_phys(cs->as, cpu->env.psa + pswoffset + 8));
1936     s390_cpu_halt(cpu);
1937     qemu_system_guest_panicked(NULL);
1938 }
1939 
1940 /* try to detect pgm check loops */
1941 static int handle_oper_loop(S390CPU *cpu, struct kvm_run *run)
1942 {
1943     CPUState *cs = CPU(cpu);
1944     PSW oldpsw, newpsw;
1945 
1946     cpu_synchronize_state(cs);
1947     newpsw.mask = ldq_phys(cs->as, cpu->env.psa +
1948                            offsetof(LowCore, program_new_psw));
1949     newpsw.addr = ldq_phys(cs->as, cpu->env.psa +
1950                            offsetof(LowCore, program_new_psw) + 8);
1951     oldpsw.mask  = run->psw_mask;
1952     oldpsw.addr  = run->psw_addr;
1953     /*
1954      * Avoid endless loops of operation exceptions, if the pgm new
1955      * PSW will cause a new operation exception.
1956      * The heuristic checks if the pgm new psw is within 6 bytes before
1957      * the faulting psw address (with same DAT, AS settings) and the
1958      * new psw is not a wait psw and the fault was not triggered by
1959      * problem state. In that case go into crashed state.
1960      */
1961 
1962     if (oldpsw.addr - newpsw.addr <= 6 &&
1963         !(newpsw.mask & PSW_MASK_WAIT) &&
1964         !(oldpsw.mask & PSW_MASK_PSTATE) &&
1965         (newpsw.mask & PSW_MASK_ASC) == (oldpsw.mask & PSW_MASK_ASC) &&
1966         (newpsw.mask & PSW_MASK_DAT) == (oldpsw.mask & PSW_MASK_DAT)) {
1967         unmanageable_intercept(cpu, "operation exception loop",
1968                                offsetof(LowCore, program_new_psw));
1969         return EXCP_HALTED;
1970     }
1971     return 0;
1972 }
1973 
1974 static int handle_intercept(S390CPU *cpu)
1975 {
1976     CPUState *cs = CPU(cpu);
1977     struct kvm_run *run = cs->kvm_run;
1978     int icpt_code = run->s390_sieic.icptcode;
1979     int r = 0;
1980 
1981     DPRINTF("intercept: 0x%x (at 0x%lx)\n", icpt_code,
1982             (long)cs->kvm_run->psw_addr);
1983     switch (icpt_code) {
1984         case ICPT_INSTRUCTION:
1985             r = handle_instruction(cpu, run);
1986             break;
1987         case ICPT_PROGRAM:
1988             unmanageable_intercept(cpu, "program interrupt",
1989                                    offsetof(LowCore, program_new_psw));
1990             r = EXCP_HALTED;
1991             break;
1992         case ICPT_EXT_INT:
1993             unmanageable_intercept(cpu, "external interrupt",
1994                                    offsetof(LowCore, external_new_psw));
1995             r = EXCP_HALTED;
1996             break;
1997         case ICPT_WAITPSW:
1998             /* disabled wait, since enabled wait is handled in kernel */
1999             cpu_synchronize_state(cs);
2000             s390_handle_wait(cpu);
2001             r = EXCP_HALTED;
2002             break;
2003         case ICPT_CPU_STOP:
2004             if (s390_cpu_set_state(CPU_STATE_STOPPED, cpu) == 0) {
2005                 qemu_system_shutdown_request(SHUTDOWN_CAUSE_GUEST_SHUTDOWN);
2006             }
2007             if (cpu->env.sigp_order == SIGP_STOP_STORE_STATUS) {
2008                 s390_store_status(cpu, S390_STORE_STATUS_DEF_ADDR, true);
2009             }
2010             cpu->env.sigp_order = 0;
2011             r = EXCP_HALTED;
2012             break;
2013         case ICPT_OPEREXC:
2014             /* check for break points */
2015             r = handle_sw_breakpoint(cpu, run);
2016             if (r == -ENOENT) {
2017                 /* Then check for potential pgm check loops */
2018                 r = handle_oper_loop(cpu, run);
2019                 if (r == 0) {
2020                     kvm_s390_program_interrupt(cpu, PGM_OPERATION);
2021                 }
2022             }
2023             break;
2024         case ICPT_SOFT_INTERCEPT:
2025             fprintf(stderr, "KVM unimplemented icpt SOFT\n");
2026             exit(1);
2027             break;
2028         case ICPT_IO:
2029             fprintf(stderr, "KVM unimplemented icpt IO\n");
2030             exit(1);
2031             break;
2032         default:
2033             fprintf(stderr, "Unknown intercept code: %d\n", icpt_code);
2034             exit(1);
2035             break;
2036     }
2037 
2038     return r;
2039 }
2040 
2041 static int handle_tsch(S390CPU *cpu)
2042 {
2043     CPUState *cs = CPU(cpu);
2044     struct kvm_run *run = cs->kvm_run;
2045     int ret;
2046 
2047     cpu_synchronize_state(cs);
2048 
2049     ret = ioinst_handle_tsch(cpu, cpu->env.regs[1], run->s390_tsch.ipb);
2050     if (ret < 0) {
2051         /*
2052          * Failure.
2053          * If an I/O interrupt had been dequeued, we have to reinject it.
2054          */
2055         if (run->s390_tsch.dequeued) {
2056             kvm_s390_io_interrupt(run->s390_tsch.subchannel_id,
2057                                   run->s390_tsch.subchannel_nr,
2058                                   run->s390_tsch.io_int_parm,
2059                                   run->s390_tsch.io_int_word);
2060         }
2061         ret = 0;
2062     }
2063     return ret;
2064 }
2065 
2066 static void insert_stsi_3_2_2(S390CPU *cpu, __u64 addr, uint8_t ar)
2067 {
2068     struct sysib_322 sysib;
2069     int del;
2070 
2071     if (s390_cpu_virt_mem_read(cpu, addr, ar, &sysib, sizeof(sysib))) {
2072         return;
2073     }
2074     /* Shift the stack of Extended Names to prepare for our own data */
2075     memmove(&sysib.ext_names[1], &sysib.ext_names[0],
2076             sizeof(sysib.ext_names[0]) * (sysib.count - 1));
2077     /* First virt level, that doesn't provide Ext Names delimits stack. It is
2078      * assumed it's not capable of managing Extended Names for lower levels.
2079      */
2080     for (del = 1; del < sysib.count; del++) {
2081         if (!sysib.vm[del].ext_name_encoding || !sysib.ext_names[del][0]) {
2082             break;
2083         }
2084     }
2085     if (del < sysib.count) {
2086         memset(sysib.ext_names[del], 0,
2087                sizeof(sysib.ext_names[0]) * (sysib.count - del));
2088     }
2089     /* Insert short machine name in EBCDIC, padded with blanks */
2090     if (qemu_name) {
2091         memset(sysib.vm[0].name, 0x40, sizeof(sysib.vm[0].name));
2092         ebcdic_put(sysib.vm[0].name, qemu_name, MIN(sizeof(sysib.vm[0].name),
2093                                                     strlen(qemu_name)));
2094     }
2095     sysib.vm[0].ext_name_encoding = 2; /* 2 = UTF-8 */
2096     memset(sysib.ext_names[0], 0, sizeof(sysib.ext_names[0]));
2097     /* If hypervisor specifies zero Extended Name in STSI322 SYSIB, it's
2098      * considered by s390 as not capable of providing any Extended Name.
2099      * Therefore if no name was specified on qemu invocation, we go with the
2100      * same "KVMguest" default, which KVM has filled into short name field.
2101      */
2102     if (qemu_name) {
2103         strncpy((char *)sysib.ext_names[0], qemu_name,
2104                 sizeof(sysib.ext_names[0]));
2105     } else {
2106         strcpy((char *)sysib.ext_names[0], "KVMguest");
2107     }
2108     /* Insert UUID */
2109     memcpy(sysib.vm[0].uuid, &qemu_uuid, sizeof(sysib.vm[0].uuid));
2110 
2111     s390_cpu_virt_mem_write(cpu, addr, ar, &sysib, sizeof(sysib));
2112 }
2113 
2114 static int handle_stsi(S390CPU *cpu)
2115 {
2116     CPUState *cs = CPU(cpu);
2117     struct kvm_run *run = cs->kvm_run;
2118 
2119     switch (run->s390_stsi.fc) {
2120     case 3:
2121         if (run->s390_stsi.sel1 != 2 || run->s390_stsi.sel2 != 2) {
2122             return 0;
2123         }
2124         /* Only sysib 3.2.2 needs post-handling for now. */
2125         insert_stsi_3_2_2(cpu, run->s390_stsi.addr, run->s390_stsi.ar);
2126         return 0;
2127     default:
2128         return 0;
2129     }
2130 }
2131 
2132 static int kvm_arch_handle_debug_exit(S390CPU *cpu)
2133 {
2134     CPUState *cs = CPU(cpu);
2135     struct kvm_run *run = cs->kvm_run;
2136 
2137     int ret = 0;
2138     struct kvm_debug_exit_arch *arch_info = &run->debug.arch;
2139 
2140     switch (arch_info->type) {
2141     case KVM_HW_WP_WRITE:
2142         if (find_hw_breakpoint(arch_info->addr, -1, arch_info->type)) {
2143             cs->watchpoint_hit = &hw_watchpoint;
2144             hw_watchpoint.vaddr = arch_info->addr;
2145             hw_watchpoint.flags = BP_MEM_WRITE;
2146             ret = EXCP_DEBUG;
2147         }
2148         break;
2149     case KVM_HW_BP:
2150         if (find_hw_breakpoint(arch_info->addr, -1, arch_info->type)) {
2151             ret = EXCP_DEBUG;
2152         }
2153         break;
2154     case KVM_SINGLESTEP:
2155         if (cs->singlestep_enabled) {
2156             ret = EXCP_DEBUG;
2157         }
2158         break;
2159     default:
2160         ret = -ENOSYS;
2161     }
2162 
2163     return ret;
2164 }
2165 
2166 int kvm_arch_handle_exit(CPUState *cs, struct kvm_run *run)
2167 {
2168     S390CPU *cpu = S390_CPU(cs);
2169     int ret = 0;
2170 
2171     qemu_mutex_lock_iothread();
2172 
2173     switch (run->exit_reason) {
2174         case KVM_EXIT_S390_SIEIC:
2175             ret = handle_intercept(cpu);
2176             break;
2177         case KVM_EXIT_S390_RESET:
2178             s390_reipl_request();
2179             break;
2180         case KVM_EXIT_S390_TSCH:
2181             ret = handle_tsch(cpu);
2182             break;
2183         case KVM_EXIT_S390_STSI:
2184             ret = handle_stsi(cpu);
2185             break;
2186         case KVM_EXIT_DEBUG:
2187             ret = kvm_arch_handle_debug_exit(cpu);
2188             break;
2189         default:
2190             fprintf(stderr, "Unknown KVM exit: %d\n", run->exit_reason);
2191             break;
2192     }
2193     qemu_mutex_unlock_iothread();
2194 
2195     if (ret == 0) {
2196         ret = EXCP_INTERRUPT;
2197     }
2198     return ret;
2199 }
2200 
2201 bool kvm_arch_stop_on_emulation_error(CPUState *cpu)
2202 {
2203     return true;
2204 }
2205 
2206 void kvm_s390_io_interrupt(uint16_t subchannel_id,
2207                            uint16_t subchannel_nr, uint32_t io_int_parm,
2208                            uint32_t io_int_word)
2209 {
2210     struct kvm_s390_irq irq = {
2211         .u.io.subchannel_id = subchannel_id,
2212         .u.io.subchannel_nr = subchannel_nr,
2213         .u.io.io_int_parm = io_int_parm,
2214         .u.io.io_int_word = io_int_word,
2215     };
2216 
2217     if (io_int_word & IO_INT_WORD_AI) {
2218         irq.type = KVM_S390_INT_IO(1, 0, 0, 0);
2219     } else {
2220         irq.type = KVM_S390_INT_IO(0, (subchannel_id & 0xff00) >> 8,
2221                                       (subchannel_id & 0x0006),
2222                                       subchannel_nr);
2223     }
2224     kvm_s390_floating_interrupt(&irq);
2225 }
2226 
2227 static uint64_t build_channel_report_mcic(void)
2228 {
2229     uint64_t mcic;
2230 
2231     /* subclass: indicate channel report pending */
2232     mcic = MCIC_SC_CP |
2233     /* subclass modifiers: none */
2234     /* storage errors: none */
2235     /* validity bits: no damage */
2236         MCIC_VB_WP | MCIC_VB_MS | MCIC_VB_PM | MCIC_VB_IA | MCIC_VB_FP |
2237         MCIC_VB_GR | MCIC_VB_CR | MCIC_VB_ST | MCIC_VB_AR | MCIC_VB_PR |
2238         MCIC_VB_FC | MCIC_VB_CT | MCIC_VB_CC;
2239     if (s390_has_feat(S390_FEAT_VECTOR)) {
2240         mcic |= MCIC_VB_VR;
2241     }
2242     if (s390_has_feat(S390_FEAT_GUARDED_STORAGE)) {
2243         mcic |= MCIC_VB_GS;
2244     }
2245     return mcic;
2246 }
2247 
2248 void kvm_s390_crw_mchk(void)
2249 {
2250     struct kvm_s390_irq irq = {
2251         .type = KVM_S390_MCHK,
2252         .u.mchk.cr14 = 1 << 28,
2253         .u.mchk.mcic = build_channel_report_mcic(),
2254     };
2255     kvm_s390_floating_interrupt(&irq);
2256 }
2257 
2258 void kvm_s390_enable_css_support(S390CPU *cpu)
2259 {
2260     int r;
2261 
2262     /* Activate host kernel channel subsystem support. */
2263     r = kvm_vcpu_enable_cap(CPU(cpu), KVM_CAP_S390_CSS_SUPPORT, 0);
2264     assert(r == 0);
2265 }
2266 
2267 void kvm_arch_init_irq_routing(KVMState *s)
2268 {
2269     /*
2270      * Note that while irqchip capabilities generally imply that cpustates
2271      * are handled in-kernel, it is not true for s390 (yet); therefore, we
2272      * have to override the common code kvm_halt_in_kernel_allowed setting.
2273      */
2274     if (kvm_check_extension(s, KVM_CAP_IRQ_ROUTING)) {
2275         kvm_gsi_routing_allowed = true;
2276         kvm_halt_in_kernel_allowed = false;
2277     }
2278 }
2279 
2280 int kvm_s390_assign_subch_ioeventfd(EventNotifier *notifier, uint32_t sch,
2281                                     int vq, bool assign)
2282 {
2283     struct kvm_ioeventfd kick = {
2284         .flags = KVM_IOEVENTFD_FLAG_VIRTIO_CCW_NOTIFY |
2285         KVM_IOEVENTFD_FLAG_DATAMATCH,
2286         .fd = event_notifier_get_fd(notifier),
2287         .datamatch = vq,
2288         .addr = sch,
2289         .len = 8,
2290     };
2291     if (!kvm_check_extension(kvm_state, KVM_CAP_IOEVENTFD)) {
2292         return -ENOSYS;
2293     }
2294     if (!assign) {
2295         kick.flags |= KVM_IOEVENTFD_FLAG_DEASSIGN;
2296     }
2297     return kvm_vm_ioctl(kvm_state, KVM_IOEVENTFD, &kick);
2298 }
2299 
2300 int kvm_s390_get_memslot_count(void)
2301 {
2302     return kvm_check_extension(kvm_state, KVM_CAP_NR_MEMSLOTS);
2303 }
2304 
2305 int kvm_s390_get_ri(void)
2306 {
2307     return cap_ri;
2308 }
2309 
2310 int kvm_s390_get_gs(void)
2311 {
2312     return cap_gs;
2313 }
2314 
2315 int kvm_s390_set_cpu_state(S390CPU *cpu, uint8_t cpu_state)
2316 {
2317     struct kvm_mp_state mp_state = {};
2318     int ret;
2319 
2320     /* the kvm part might not have been initialized yet */
2321     if (CPU(cpu)->kvm_state == NULL) {
2322         return 0;
2323     }
2324 
2325     switch (cpu_state) {
2326     case CPU_STATE_STOPPED:
2327         mp_state.mp_state = KVM_MP_STATE_STOPPED;
2328         break;
2329     case CPU_STATE_CHECK_STOP:
2330         mp_state.mp_state = KVM_MP_STATE_CHECK_STOP;
2331         break;
2332     case CPU_STATE_OPERATING:
2333         mp_state.mp_state = KVM_MP_STATE_OPERATING;
2334         break;
2335     case CPU_STATE_LOAD:
2336         mp_state.mp_state = KVM_MP_STATE_LOAD;
2337         break;
2338     default:
2339         error_report("Requested CPU state is not a valid S390 CPU state: %u",
2340                      cpu_state);
2341         exit(1);
2342     }
2343 
2344     ret = kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MP_STATE, &mp_state);
2345     if (ret) {
2346         trace_kvm_failed_cpu_state_set(CPU(cpu)->cpu_index, cpu_state,
2347                                        strerror(-ret));
2348     }
2349 
2350     return ret;
2351 }
2352 
2353 void kvm_s390_vcpu_interrupt_pre_save(S390CPU *cpu)
2354 {
2355     struct kvm_s390_irq_state irq_state;
2356     CPUState *cs = CPU(cpu);
2357     int32_t bytes;
2358 
2359     if (!kvm_check_extension(kvm_state, KVM_CAP_S390_IRQ_STATE)) {
2360         return;
2361     }
2362 
2363     irq_state.buf = (uint64_t) cpu->irqstate;
2364     irq_state.len = VCPU_IRQ_BUF_SIZE;
2365 
2366     bytes = kvm_vcpu_ioctl(cs, KVM_S390_GET_IRQ_STATE, &irq_state);
2367     if (bytes < 0) {
2368         cpu->irqstate_saved_size = 0;
2369         error_report("Migration of interrupt state failed");
2370         return;
2371     }
2372 
2373     cpu->irqstate_saved_size = bytes;
2374 }
2375 
2376 int kvm_s390_vcpu_interrupt_post_load(S390CPU *cpu)
2377 {
2378     CPUState *cs = CPU(cpu);
2379     struct kvm_s390_irq_state irq_state;
2380     int r;
2381 
2382     if (cpu->irqstate_saved_size == 0) {
2383         return 0;
2384     }
2385 
2386     if (!kvm_check_extension(kvm_state, KVM_CAP_S390_IRQ_STATE)) {
2387         return -ENOSYS;
2388     }
2389 
2390     irq_state.buf = (uint64_t) cpu->irqstate;
2391     irq_state.len = cpu->irqstate_saved_size;
2392 
2393     r = kvm_vcpu_ioctl(cs, KVM_S390_SET_IRQ_STATE, &irq_state);
2394     if (r) {
2395         error_report("Setting interrupt state failed %d", r);
2396     }
2397     return r;
2398 }
2399 
2400 int kvm_arch_fixup_msi_route(struct kvm_irq_routing_entry *route,
2401                              uint64_t address, uint32_t data, PCIDevice *dev)
2402 {
2403     S390PCIBusDevice *pbdev;
2404     uint32_t vec = data & ZPCI_MSI_VEC_MASK;
2405 
2406     if (!dev) {
2407         DPRINTF("add_msi_route no pci device\n");
2408         return -ENODEV;
2409     }
2410 
2411     pbdev = s390_pci_find_dev_by_target(s390_get_phb(), DEVICE(dev)->id);
2412     if (!pbdev) {
2413         DPRINTF("add_msi_route no zpci device\n");
2414         return -ENODEV;
2415     }
2416 
2417     route->type = KVM_IRQ_ROUTING_S390_ADAPTER;
2418     route->flags = 0;
2419     route->u.adapter.summary_addr = pbdev->routes.adapter.summary_addr;
2420     route->u.adapter.ind_addr = pbdev->routes.adapter.ind_addr;
2421     route->u.adapter.summary_offset = pbdev->routes.adapter.summary_offset;
2422     route->u.adapter.ind_offset = pbdev->routes.adapter.ind_offset + vec;
2423     route->u.adapter.adapter_id = pbdev->routes.adapter.adapter_id;
2424     return 0;
2425 }
2426 
2427 int kvm_arch_add_msi_route_post(struct kvm_irq_routing_entry *route,
2428                                 int vector, PCIDevice *dev)
2429 {
2430     return 0;
2431 }
2432 
2433 int kvm_arch_release_virq_post(int virq)
2434 {
2435     return 0;
2436 }
2437 
2438 int kvm_arch_msi_data_to_gsi(uint32_t data)
2439 {
2440     abort();
2441 }
2442 
2443 static int query_cpu_subfunc(S390FeatBitmap features)
2444 {
2445     struct kvm_s390_vm_cpu_subfunc prop;
2446     struct kvm_device_attr attr = {
2447         .group = KVM_S390_VM_CPU_MODEL,
2448         .attr = KVM_S390_VM_CPU_MACHINE_SUBFUNC,
2449         .addr = (uint64_t) &prop,
2450     };
2451     int rc;
2452 
2453     rc = kvm_vm_ioctl(kvm_state, KVM_GET_DEVICE_ATTR, &attr);
2454     if (rc) {
2455         return  rc;
2456     }
2457 
2458     /*
2459      * We're going to add all subfunctions now, if the corresponding feature
2460      * is available that unlocks the query functions.
2461      */
2462     s390_add_from_feat_block(features, S390_FEAT_TYPE_PLO, prop.plo);
2463     if (test_bit(S390_FEAT_TOD_CLOCK_STEERING, features)) {
2464         s390_add_from_feat_block(features, S390_FEAT_TYPE_PTFF, prop.ptff);
2465     }
2466     if (test_bit(S390_FEAT_MSA, features)) {
2467         s390_add_from_feat_block(features, S390_FEAT_TYPE_KMAC, prop.kmac);
2468         s390_add_from_feat_block(features, S390_FEAT_TYPE_KMC, prop.kmc);
2469         s390_add_from_feat_block(features, S390_FEAT_TYPE_KM, prop.km);
2470         s390_add_from_feat_block(features, S390_FEAT_TYPE_KIMD, prop.kimd);
2471         s390_add_from_feat_block(features, S390_FEAT_TYPE_KLMD, prop.klmd);
2472     }
2473     if (test_bit(S390_FEAT_MSA_EXT_3, features)) {
2474         s390_add_from_feat_block(features, S390_FEAT_TYPE_PCKMO, prop.pckmo);
2475     }
2476     if (test_bit(S390_FEAT_MSA_EXT_4, features)) {
2477         s390_add_from_feat_block(features, S390_FEAT_TYPE_KMCTR, prop.kmctr);
2478         s390_add_from_feat_block(features, S390_FEAT_TYPE_KMF, prop.kmf);
2479         s390_add_from_feat_block(features, S390_FEAT_TYPE_KMO, prop.kmo);
2480         s390_add_from_feat_block(features, S390_FEAT_TYPE_PCC, prop.pcc);
2481     }
2482     if (test_bit(S390_FEAT_MSA_EXT_5, features)) {
2483         s390_add_from_feat_block(features, S390_FEAT_TYPE_PPNO, prop.ppno);
2484     }
2485     if (test_bit(S390_FEAT_MSA_EXT_8, features)) {
2486         s390_add_from_feat_block(features, S390_FEAT_TYPE_KMA, prop.kma);
2487     }
2488     return 0;
2489 }
2490 
2491 static int configure_cpu_subfunc(const S390FeatBitmap features)
2492 {
2493     struct kvm_s390_vm_cpu_subfunc prop = {};
2494     struct kvm_device_attr attr = {
2495         .group = KVM_S390_VM_CPU_MODEL,
2496         .attr = KVM_S390_VM_CPU_PROCESSOR_SUBFUNC,
2497         .addr = (uint64_t) &prop,
2498     };
2499 
2500     if (!kvm_vm_check_attr(kvm_state, KVM_S390_VM_CPU_MODEL,
2501                            KVM_S390_VM_CPU_PROCESSOR_SUBFUNC)) {
2502         /* hardware support might be missing, IBC will handle most of this */
2503         return 0;
2504     }
2505 
2506     s390_fill_feat_block(features, S390_FEAT_TYPE_PLO, prop.plo);
2507     if (test_bit(S390_FEAT_TOD_CLOCK_STEERING, features)) {
2508         s390_fill_feat_block(features, S390_FEAT_TYPE_PTFF, prop.ptff);
2509     }
2510     if (test_bit(S390_FEAT_MSA, features)) {
2511         s390_fill_feat_block(features, S390_FEAT_TYPE_KMAC, prop.kmac);
2512         s390_fill_feat_block(features, S390_FEAT_TYPE_KMC, prop.kmc);
2513         s390_fill_feat_block(features, S390_FEAT_TYPE_KM, prop.km);
2514         s390_fill_feat_block(features, S390_FEAT_TYPE_KIMD, prop.kimd);
2515         s390_fill_feat_block(features, S390_FEAT_TYPE_KLMD, prop.klmd);
2516     }
2517     if (test_bit(S390_FEAT_MSA_EXT_3, features)) {
2518         s390_fill_feat_block(features, S390_FEAT_TYPE_PCKMO, prop.pckmo);
2519     }
2520     if (test_bit(S390_FEAT_MSA_EXT_4, features)) {
2521         s390_fill_feat_block(features, S390_FEAT_TYPE_KMCTR, prop.kmctr);
2522         s390_fill_feat_block(features, S390_FEAT_TYPE_KMF, prop.kmf);
2523         s390_fill_feat_block(features, S390_FEAT_TYPE_KMO, prop.kmo);
2524         s390_fill_feat_block(features, S390_FEAT_TYPE_PCC, prop.pcc);
2525     }
2526     if (test_bit(S390_FEAT_MSA_EXT_5, features)) {
2527         s390_fill_feat_block(features, S390_FEAT_TYPE_PPNO, prop.ppno);
2528     }
2529     if (test_bit(S390_FEAT_MSA_EXT_8, features)) {
2530         s390_fill_feat_block(features, S390_FEAT_TYPE_KMA, prop.kma);
2531     }
2532     return kvm_vm_ioctl(kvm_state, KVM_SET_DEVICE_ATTR, &attr);
2533 }
2534 
2535 static int kvm_to_feat[][2] = {
2536     { KVM_S390_VM_CPU_FEAT_ESOP, S390_FEAT_ESOP },
2537     { KVM_S390_VM_CPU_FEAT_SIEF2, S390_FEAT_SIE_F2 },
2538     { KVM_S390_VM_CPU_FEAT_64BSCAO , S390_FEAT_SIE_64BSCAO },
2539     { KVM_S390_VM_CPU_FEAT_SIIF, S390_FEAT_SIE_SIIF },
2540     { KVM_S390_VM_CPU_FEAT_GPERE, S390_FEAT_SIE_GPERE },
2541     { KVM_S390_VM_CPU_FEAT_GSLS, S390_FEAT_SIE_GSLS },
2542     { KVM_S390_VM_CPU_FEAT_IB, S390_FEAT_SIE_IB },
2543     { KVM_S390_VM_CPU_FEAT_CEI, S390_FEAT_SIE_CEI },
2544     { KVM_S390_VM_CPU_FEAT_IBS, S390_FEAT_SIE_IBS },
2545     { KVM_S390_VM_CPU_FEAT_SKEY, S390_FEAT_SIE_SKEY },
2546     { KVM_S390_VM_CPU_FEAT_CMMA, S390_FEAT_SIE_CMMA },
2547     { KVM_S390_VM_CPU_FEAT_PFMFI, S390_FEAT_SIE_PFMFI},
2548     { KVM_S390_VM_CPU_FEAT_SIGPIF, S390_FEAT_SIE_SIGPIF},
2549     { KVM_S390_VM_CPU_FEAT_KSS, S390_FEAT_SIE_KSS},
2550 };
2551 
2552 static int query_cpu_feat(S390FeatBitmap features)
2553 {
2554     struct kvm_s390_vm_cpu_feat prop;
2555     struct kvm_device_attr attr = {
2556         .group = KVM_S390_VM_CPU_MODEL,
2557         .attr = KVM_S390_VM_CPU_MACHINE_FEAT,
2558         .addr = (uint64_t) &prop,
2559     };
2560     int rc;
2561     int i;
2562 
2563     rc = kvm_vm_ioctl(kvm_state, KVM_GET_DEVICE_ATTR, &attr);
2564     if (rc) {
2565         return  rc;
2566     }
2567 
2568     for (i = 0; i < ARRAY_SIZE(kvm_to_feat); i++) {
2569         if (test_be_bit(kvm_to_feat[i][0], (uint8_t *) prop.feat)) {
2570             set_bit(kvm_to_feat[i][1], features);
2571         }
2572     }
2573     return 0;
2574 }
2575 
2576 static int configure_cpu_feat(const S390FeatBitmap features)
2577 {
2578     struct kvm_s390_vm_cpu_feat prop = {};
2579     struct kvm_device_attr attr = {
2580         .group = KVM_S390_VM_CPU_MODEL,
2581         .attr = KVM_S390_VM_CPU_PROCESSOR_FEAT,
2582         .addr = (uint64_t) &prop,
2583     };
2584     int i;
2585 
2586     for (i = 0; i < ARRAY_SIZE(kvm_to_feat); i++) {
2587         if (test_bit(kvm_to_feat[i][1], features)) {
2588             set_be_bit(kvm_to_feat[i][0], (uint8_t *) prop.feat);
2589         }
2590     }
2591     return kvm_vm_ioctl(kvm_state, KVM_SET_DEVICE_ATTR, &attr);
2592 }
2593 
2594 bool kvm_s390_cpu_models_supported(void)
2595 {
2596     if (!cpu_model_allowed()) {
2597         /* compatibility machines interfere with the cpu model */
2598         return false;
2599     }
2600     return kvm_vm_check_attr(kvm_state, KVM_S390_VM_CPU_MODEL,
2601                              KVM_S390_VM_CPU_MACHINE) &&
2602            kvm_vm_check_attr(kvm_state, KVM_S390_VM_CPU_MODEL,
2603                              KVM_S390_VM_CPU_PROCESSOR) &&
2604            kvm_vm_check_attr(kvm_state, KVM_S390_VM_CPU_MODEL,
2605                              KVM_S390_VM_CPU_MACHINE_FEAT) &&
2606            kvm_vm_check_attr(kvm_state, KVM_S390_VM_CPU_MODEL,
2607                              KVM_S390_VM_CPU_PROCESSOR_FEAT) &&
2608            kvm_vm_check_attr(kvm_state, KVM_S390_VM_CPU_MODEL,
2609                              KVM_S390_VM_CPU_MACHINE_SUBFUNC);
2610 }
2611 
2612 void kvm_s390_get_host_cpu_model(S390CPUModel *model, Error **errp)
2613 {
2614     struct kvm_s390_vm_cpu_machine prop = {};
2615     struct kvm_device_attr attr = {
2616         .group = KVM_S390_VM_CPU_MODEL,
2617         .attr = KVM_S390_VM_CPU_MACHINE,
2618         .addr = (uint64_t) &prop,
2619     };
2620     uint16_t unblocked_ibc = 0, cpu_type = 0;
2621     int rc;
2622 
2623     memset(model, 0, sizeof(*model));
2624 
2625     if (!kvm_s390_cpu_models_supported()) {
2626         error_setg(errp, "KVM doesn't support CPU models");
2627         return;
2628     }
2629 
2630     /* query the basic cpu model properties */
2631     rc = kvm_vm_ioctl(kvm_state, KVM_GET_DEVICE_ATTR, &attr);
2632     if (rc) {
2633         error_setg(errp, "KVM: Error querying host CPU model: %d", rc);
2634         return;
2635     }
2636 
2637     cpu_type = cpuid_type(prop.cpuid);
2638     if (has_ibc(prop.ibc)) {
2639         model->lowest_ibc = lowest_ibc(prop.ibc);
2640         unblocked_ibc = unblocked_ibc(prop.ibc);
2641     }
2642     model->cpu_id = cpuid_id(prop.cpuid);
2643     model->cpu_id_format = cpuid_format(prop.cpuid);
2644     model->cpu_ver = 0xff;
2645 
2646     /* get supported cpu features indicated via STFL(E) */
2647     s390_add_from_feat_block(model->features, S390_FEAT_TYPE_STFL,
2648                              (uint8_t *) prop.fac_mask);
2649     /* dat-enhancement facility 2 has no bit but was introduced with stfle */
2650     if (test_bit(S390_FEAT_STFLE, model->features)) {
2651         set_bit(S390_FEAT_DAT_ENH_2, model->features);
2652     }
2653     /* get supported cpu features indicated e.g. via SCLP */
2654     rc = query_cpu_feat(model->features);
2655     if (rc) {
2656         error_setg(errp, "KVM: Error querying CPU features: %d", rc);
2657         return;
2658     }
2659     /* get supported cpu subfunctions indicated via query / test bit */
2660     rc = query_cpu_subfunc(model->features);
2661     if (rc) {
2662         error_setg(errp, "KVM: Error querying CPU subfunctions: %d", rc);
2663         return;
2664     }
2665 
2666     /* with cpu model support, CMM is only indicated if really available */
2667     if (kvm_s390_cmma_available()) {
2668         set_bit(S390_FEAT_CMM, model->features);
2669     } else {
2670         /* no cmm -> no cmm nt */
2671         clear_bit(S390_FEAT_CMM_NT, model->features);
2672     }
2673 
2674     /* We emulate a zPCI bus and AEN, therefore we don't need HW support */
2675     if (pci_available) {
2676         set_bit(S390_FEAT_ZPCI, model->features);
2677     }
2678     set_bit(S390_FEAT_ADAPTER_EVENT_NOTIFICATION, model->features);
2679 
2680     if (s390_known_cpu_type(cpu_type)) {
2681         /* we want the exact model, even if some features are missing */
2682         model->def = s390_find_cpu_def(cpu_type, ibc_gen(unblocked_ibc),
2683                                        ibc_ec_ga(unblocked_ibc), NULL);
2684     } else {
2685         /* model unknown, e.g. too new - search using features */
2686         model->def = s390_find_cpu_def(0, ibc_gen(unblocked_ibc),
2687                                        ibc_ec_ga(unblocked_ibc),
2688                                        model->features);
2689     }
2690     if (!model->def) {
2691         error_setg(errp, "KVM: host CPU model could not be identified");
2692         return;
2693     }
2694     /* strip of features that are not part of the maximum model */
2695     bitmap_and(model->features, model->features, model->def->full_feat,
2696                S390_FEAT_MAX);
2697 }
2698 
2699 void kvm_s390_apply_cpu_model(const S390CPUModel *model, Error **errp)
2700 {
2701     struct kvm_s390_vm_cpu_processor prop  = {
2702         .fac_list = { 0 },
2703     };
2704     struct kvm_device_attr attr = {
2705         .group = KVM_S390_VM_CPU_MODEL,
2706         .attr = KVM_S390_VM_CPU_PROCESSOR,
2707         .addr = (uint64_t) &prop,
2708     };
2709     int rc;
2710 
2711     if (!model) {
2712         /* compatibility handling if cpu models are disabled */
2713         if (kvm_s390_cmma_available()) {
2714             kvm_s390_enable_cmma();
2715         }
2716         return;
2717     }
2718     if (!kvm_s390_cpu_models_supported()) {
2719         error_setg(errp, "KVM doesn't support CPU models");
2720         return;
2721     }
2722     prop.cpuid = s390_cpuid_from_cpu_model(model);
2723     prop.ibc = s390_ibc_from_cpu_model(model);
2724     /* configure cpu features indicated via STFL(e) */
2725     s390_fill_feat_block(model->features, S390_FEAT_TYPE_STFL,
2726                          (uint8_t *) prop.fac_list);
2727     rc = kvm_vm_ioctl(kvm_state, KVM_SET_DEVICE_ATTR, &attr);
2728     if (rc) {
2729         error_setg(errp, "KVM: Error configuring the CPU model: %d", rc);
2730         return;
2731     }
2732     /* configure cpu features indicated e.g. via SCLP */
2733     rc = configure_cpu_feat(model->features);
2734     if (rc) {
2735         error_setg(errp, "KVM: Error configuring CPU features: %d", rc);
2736         return;
2737     }
2738     /* configure cpu subfunctions indicated via query / test bit */
2739     rc = configure_cpu_subfunc(model->features);
2740     if (rc) {
2741         error_setg(errp, "KVM: Error configuring CPU subfunctions: %d", rc);
2742         return;
2743     }
2744     /* enable CMM via CMMA */
2745     if (test_bit(S390_FEAT_CMM, model->features)) {
2746         kvm_s390_enable_cmma();
2747     }
2748 }
2749 
2750 void kvm_s390_restart_interrupt(S390CPU *cpu)
2751 {
2752     struct kvm_s390_irq irq = {
2753         .type = KVM_S390_RESTART,
2754     };
2755 
2756     kvm_s390_vcpu_interrupt(cpu, &irq);
2757 }
2758 
2759 void kvm_s390_stop_interrupt(S390CPU *cpu)
2760 {
2761     struct kvm_s390_irq irq = {
2762         .type = KVM_S390_SIGP_STOP,
2763     };
2764 
2765     kvm_s390_vcpu_interrupt(cpu, &irq);
2766 }
2767