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