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