GNU Linux-libre 6.1.90-gnu
[releases.git] / arch / s390 / kvm / kvm-s390.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * hosting IBM Z kernel virtual machines (s390x)
4  *
5  * Copyright IBM Corp. 2008, 2020
6  *
7  *    Author(s): Carsten Otte <cotte@de.ibm.com>
8  *               Christian Borntraeger <borntraeger@de.ibm.com>
9  *               Christian Ehrhardt <ehrhardt@de.ibm.com>
10  *               Jason J. Herne <jjherne@us.ibm.com>
11  */
12
13 #define KMSG_COMPONENT "kvm-s390"
14 #define pr_fmt(fmt) KMSG_COMPONENT ": " fmt
15
16 #include <linux/compiler.h>
17 #include <linux/err.h>
18 #include <linux/fs.h>
19 #include <linux/hrtimer.h>
20 #include <linux/init.h>
21 #include <linux/kvm.h>
22 #include <linux/kvm_host.h>
23 #include <linux/mman.h>
24 #include <linux/module.h>
25 #include <linux/moduleparam.h>
26 #include <linux/random.h>
27 #include <linux/slab.h>
28 #include <linux/timer.h>
29 #include <linux/vmalloc.h>
30 #include <linux/bitmap.h>
31 #include <linux/sched/signal.h>
32 #include <linux/string.h>
33 #include <linux/pgtable.h>
34 #include <linux/mmu_notifier.h>
35
36 #include <asm/asm-offsets.h>
37 #include <asm/lowcore.h>
38 #include <asm/stp.h>
39 #include <asm/gmap.h>
40 #include <asm/nmi.h>
41 #include <asm/switch_to.h>
42 #include <asm/isc.h>
43 #include <asm/sclp.h>
44 #include <asm/cpacf.h>
45 #include <asm/timex.h>
46 #include <asm/ap.h>
47 #include <asm/uv.h>
48 #include <asm/fpu/api.h>
49 #include "kvm-s390.h"
50 #include "gaccess.h"
51 #include "pci.h"
52
53 #define CREATE_TRACE_POINTS
54 #include "trace.h"
55 #include "trace-s390.h"
56
57 #define MEM_OP_MAX_SIZE 65536   /* Maximum transfer size for KVM_S390_MEM_OP */
58 #define LOCAL_IRQS 32
59 #define VCPU_IRQS_MAX_BUF (sizeof(struct kvm_s390_irq) * \
60                            (KVM_MAX_VCPUS + LOCAL_IRQS))
61
62 const struct _kvm_stats_desc kvm_vm_stats_desc[] = {
63         KVM_GENERIC_VM_STATS(),
64         STATS_DESC_COUNTER(VM, inject_io),
65         STATS_DESC_COUNTER(VM, inject_float_mchk),
66         STATS_DESC_COUNTER(VM, inject_pfault_done),
67         STATS_DESC_COUNTER(VM, inject_service_signal),
68         STATS_DESC_COUNTER(VM, inject_virtio),
69         STATS_DESC_COUNTER(VM, aen_forward),
70         STATS_DESC_COUNTER(VM, gmap_shadow_reuse),
71         STATS_DESC_COUNTER(VM, gmap_shadow_create),
72         STATS_DESC_COUNTER(VM, gmap_shadow_r1_entry),
73         STATS_DESC_COUNTER(VM, gmap_shadow_r2_entry),
74         STATS_DESC_COUNTER(VM, gmap_shadow_r3_entry),
75         STATS_DESC_COUNTER(VM, gmap_shadow_sg_entry),
76         STATS_DESC_COUNTER(VM, gmap_shadow_pg_entry),
77 };
78
79 const struct kvm_stats_header kvm_vm_stats_header = {
80         .name_size = KVM_STATS_NAME_SIZE,
81         .num_desc = ARRAY_SIZE(kvm_vm_stats_desc),
82         .id_offset = sizeof(struct kvm_stats_header),
83         .desc_offset = sizeof(struct kvm_stats_header) + KVM_STATS_NAME_SIZE,
84         .data_offset = sizeof(struct kvm_stats_header) + KVM_STATS_NAME_SIZE +
85                        sizeof(kvm_vm_stats_desc),
86 };
87
88 const struct _kvm_stats_desc kvm_vcpu_stats_desc[] = {
89         KVM_GENERIC_VCPU_STATS(),
90         STATS_DESC_COUNTER(VCPU, exit_userspace),
91         STATS_DESC_COUNTER(VCPU, exit_null),
92         STATS_DESC_COUNTER(VCPU, exit_external_request),
93         STATS_DESC_COUNTER(VCPU, exit_io_request),
94         STATS_DESC_COUNTER(VCPU, exit_external_interrupt),
95         STATS_DESC_COUNTER(VCPU, exit_stop_request),
96         STATS_DESC_COUNTER(VCPU, exit_validity),
97         STATS_DESC_COUNTER(VCPU, exit_instruction),
98         STATS_DESC_COUNTER(VCPU, exit_pei),
99         STATS_DESC_COUNTER(VCPU, halt_no_poll_steal),
100         STATS_DESC_COUNTER(VCPU, instruction_lctl),
101         STATS_DESC_COUNTER(VCPU, instruction_lctlg),
102         STATS_DESC_COUNTER(VCPU, instruction_stctl),
103         STATS_DESC_COUNTER(VCPU, instruction_stctg),
104         STATS_DESC_COUNTER(VCPU, exit_program_interruption),
105         STATS_DESC_COUNTER(VCPU, exit_instr_and_program),
106         STATS_DESC_COUNTER(VCPU, exit_operation_exception),
107         STATS_DESC_COUNTER(VCPU, deliver_ckc),
108         STATS_DESC_COUNTER(VCPU, deliver_cputm),
109         STATS_DESC_COUNTER(VCPU, deliver_external_call),
110         STATS_DESC_COUNTER(VCPU, deliver_emergency_signal),
111         STATS_DESC_COUNTER(VCPU, deliver_service_signal),
112         STATS_DESC_COUNTER(VCPU, deliver_virtio),
113         STATS_DESC_COUNTER(VCPU, deliver_stop_signal),
114         STATS_DESC_COUNTER(VCPU, deliver_prefix_signal),
115         STATS_DESC_COUNTER(VCPU, deliver_restart_signal),
116         STATS_DESC_COUNTER(VCPU, deliver_program),
117         STATS_DESC_COUNTER(VCPU, deliver_io),
118         STATS_DESC_COUNTER(VCPU, deliver_machine_check),
119         STATS_DESC_COUNTER(VCPU, exit_wait_state),
120         STATS_DESC_COUNTER(VCPU, inject_ckc),
121         STATS_DESC_COUNTER(VCPU, inject_cputm),
122         STATS_DESC_COUNTER(VCPU, inject_external_call),
123         STATS_DESC_COUNTER(VCPU, inject_emergency_signal),
124         STATS_DESC_COUNTER(VCPU, inject_mchk),
125         STATS_DESC_COUNTER(VCPU, inject_pfault_init),
126         STATS_DESC_COUNTER(VCPU, inject_program),
127         STATS_DESC_COUNTER(VCPU, inject_restart),
128         STATS_DESC_COUNTER(VCPU, inject_set_prefix),
129         STATS_DESC_COUNTER(VCPU, inject_stop_signal),
130         STATS_DESC_COUNTER(VCPU, instruction_epsw),
131         STATS_DESC_COUNTER(VCPU, instruction_gs),
132         STATS_DESC_COUNTER(VCPU, instruction_io_other),
133         STATS_DESC_COUNTER(VCPU, instruction_lpsw),
134         STATS_DESC_COUNTER(VCPU, instruction_lpswe),
135         STATS_DESC_COUNTER(VCPU, instruction_pfmf),
136         STATS_DESC_COUNTER(VCPU, instruction_ptff),
137         STATS_DESC_COUNTER(VCPU, instruction_sck),
138         STATS_DESC_COUNTER(VCPU, instruction_sckpf),
139         STATS_DESC_COUNTER(VCPU, instruction_stidp),
140         STATS_DESC_COUNTER(VCPU, instruction_spx),
141         STATS_DESC_COUNTER(VCPU, instruction_stpx),
142         STATS_DESC_COUNTER(VCPU, instruction_stap),
143         STATS_DESC_COUNTER(VCPU, instruction_iske),
144         STATS_DESC_COUNTER(VCPU, instruction_ri),
145         STATS_DESC_COUNTER(VCPU, instruction_rrbe),
146         STATS_DESC_COUNTER(VCPU, instruction_sske),
147         STATS_DESC_COUNTER(VCPU, instruction_ipte_interlock),
148         STATS_DESC_COUNTER(VCPU, instruction_stsi),
149         STATS_DESC_COUNTER(VCPU, instruction_stfl),
150         STATS_DESC_COUNTER(VCPU, instruction_tb),
151         STATS_DESC_COUNTER(VCPU, instruction_tpi),
152         STATS_DESC_COUNTER(VCPU, instruction_tprot),
153         STATS_DESC_COUNTER(VCPU, instruction_tsch),
154         STATS_DESC_COUNTER(VCPU, instruction_sie),
155         STATS_DESC_COUNTER(VCPU, instruction_essa),
156         STATS_DESC_COUNTER(VCPU, instruction_sthyi),
157         STATS_DESC_COUNTER(VCPU, instruction_sigp_sense),
158         STATS_DESC_COUNTER(VCPU, instruction_sigp_sense_running),
159         STATS_DESC_COUNTER(VCPU, instruction_sigp_external_call),
160         STATS_DESC_COUNTER(VCPU, instruction_sigp_emergency),
161         STATS_DESC_COUNTER(VCPU, instruction_sigp_cond_emergency),
162         STATS_DESC_COUNTER(VCPU, instruction_sigp_start),
163         STATS_DESC_COUNTER(VCPU, instruction_sigp_stop),
164         STATS_DESC_COUNTER(VCPU, instruction_sigp_stop_store_status),
165         STATS_DESC_COUNTER(VCPU, instruction_sigp_store_status),
166         STATS_DESC_COUNTER(VCPU, instruction_sigp_store_adtl_status),
167         STATS_DESC_COUNTER(VCPU, instruction_sigp_arch),
168         STATS_DESC_COUNTER(VCPU, instruction_sigp_prefix),
169         STATS_DESC_COUNTER(VCPU, instruction_sigp_restart),
170         STATS_DESC_COUNTER(VCPU, instruction_sigp_init_cpu_reset),
171         STATS_DESC_COUNTER(VCPU, instruction_sigp_cpu_reset),
172         STATS_DESC_COUNTER(VCPU, instruction_sigp_unknown),
173         STATS_DESC_COUNTER(VCPU, instruction_diagnose_10),
174         STATS_DESC_COUNTER(VCPU, instruction_diagnose_44),
175         STATS_DESC_COUNTER(VCPU, instruction_diagnose_9c),
176         STATS_DESC_COUNTER(VCPU, diag_9c_ignored),
177         STATS_DESC_COUNTER(VCPU, diag_9c_forward),
178         STATS_DESC_COUNTER(VCPU, instruction_diagnose_258),
179         STATS_DESC_COUNTER(VCPU, instruction_diagnose_308),
180         STATS_DESC_COUNTER(VCPU, instruction_diagnose_500),
181         STATS_DESC_COUNTER(VCPU, instruction_diagnose_other),
182         STATS_DESC_COUNTER(VCPU, pfault_sync)
183 };
184
185 const struct kvm_stats_header kvm_vcpu_stats_header = {
186         .name_size = KVM_STATS_NAME_SIZE,
187         .num_desc = ARRAY_SIZE(kvm_vcpu_stats_desc),
188         .id_offset = sizeof(struct kvm_stats_header),
189         .desc_offset = sizeof(struct kvm_stats_header) + KVM_STATS_NAME_SIZE,
190         .data_offset = sizeof(struct kvm_stats_header) + KVM_STATS_NAME_SIZE +
191                        sizeof(kvm_vcpu_stats_desc),
192 };
193
194 /* allow nested virtualization in KVM (if enabled by user space) */
195 static int nested;
196 module_param(nested, int, S_IRUGO);
197 MODULE_PARM_DESC(nested, "Nested virtualization support");
198
199 /* allow 1m huge page guest backing, if !nested */
200 static int hpage;
201 module_param(hpage, int, 0444);
202 MODULE_PARM_DESC(hpage, "1m huge page backing support");
203
204 /* maximum percentage of steal time for polling.  >100 is treated like 100 */
205 static u8 halt_poll_max_steal = 10;
206 module_param(halt_poll_max_steal, byte, 0644);
207 MODULE_PARM_DESC(halt_poll_max_steal, "Maximum percentage of steal time to allow polling");
208
209 /* if set to true, the GISA will be initialized and used if available */
210 static bool use_gisa  = true;
211 module_param(use_gisa, bool, 0644);
212 MODULE_PARM_DESC(use_gisa, "Use the GISA if the host supports it.");
213
214 /* maximum diag9c forwarding per second */
215 unsigned int diag9c_forwarding_hz;
216 module_param(diag9c_forwarding_hz, uint, 0644);
217 MODULE_PARM_DESC(diag9c_forwarding_hz, "Maximum diag9c forwarding per second, 0 to turn off");
218
219 /*
220  * For now we handle at most 16 double words as this is what the s390 base
221  * kernel handles and stores in the prefix page. If we ever need to go beyond
222  * this, this requires changes to code, but the external uapi can stay.
223  */
224 #define SIZE_INTERNAL 16
225
226 /*
227  * Base feature mask that defines default mask for facilities. Consists of the
228  * defines in FACILITIES_KVM and the non-hypervisor managed bits.
229  */
230 static unsigned long kvm_s390_fac_base[SIZE_INTERNAL] = { FACILITIES_KVM };
231 /*
232  * Extended feature mask. Consists of the defines in FACILITIES_KVM_CPUMODEL
233  * and defines the facilities that can be enabled via a cpu model.
234  */
235 static unsigned long kvm_s390_fac_ext[SIZE_INTERNAL] = { FACILITIES_KVM_CPUMODEL };
236
237 static unsigned long kvm_s390_fac_size(void)
238 {
239         BUILD_BUG_ON(SIZE_INTERNAL > S390_ARCH_FAC_MASK_SIZE_U64);
240         BUILD_BUG_ON(SIZE_INTERNAL > S390_ARCH_FAC_LIST_SIZE_U64);
241         BUILD_BUG_ON(SIZE_INTERNAL * sizeof(unsigned long) >
242                 sizeof(stfle_fac_list));
243
244         return SIZE_INTERNAL;
245 }
246
247 /* available cpu features supported by kvm */
248 static DECLARE_BITMAP(kvm_s390_available_cpu_feat, KVM_S390_VM_CPU_FEAT_NR_BITS);
249 /* available subfunctions indicated via query / "test bit" */
250 static struct kvm_s390_vm_cpu_subfunc kvm_s390_available_subfunc;
251
252 static struct gmap_notifier gmap_notifier;
253 static struct gmap_notifier vsie_gmap_notifier;
254 debug_info_t *kvm_s390_dbf;
255 debug_info_t *kvm_s390_dbf_uv;
256
257 /* Section: not file related */
258 int kvm_arch_hardware_enable(void)
259 {
260         /* every s390 is virtualization enabled ;-) */
261         return 0;
262 }
263
264 int kvm_arch_check_processor_compat(void *opaque)
265 {
266         return 0;
267 }
268
269 /* forward declarations */
270 static void kvm_gmap_notifier(struct gmap *gmap, unsigned long start,
271                               unsigned long end);
272 static int sca_switch_to_extended(struct kvm *kvm);
273
274 static void kvm_clock_sync_scb(struct kvm_s390_sie_block *scb, u64 delta)
275 {
276         u8 delta_idx = 0;
277
278         /*
279          * The TOD jumps by delta, we have to compensate this by adding
280          * -delta to the epoch.
281          */
282         delta = -delta;
283
284         /* sign-extension - we're adding to signed values below */
285         if ((s64)delta < 0)
286                 delta_idx = -1;
287
288         scb->epoch += delta;
289         if (scb->ecd & ECD_MEF) {
290                 scb->epdx += delta_idx;
291                 if (scb->epoch < delta)
292                         scb->epdx += 1;
293         }
294 }
295
296 /*
297  * This callback is executed during stop_machine(). All CPUs are therefore
298  * temporarily stopped. In order not to change guest behavior, we have to
299  * disable preemption whenever we touch the epoch of kvm and the VCPUs,
300  * so a CPU won't be stopped while calculating with the epoch.
301  */
302 static int kvm_clock_sync(struct notifier_block *notifier, unsigned long val,
303                           void *v)
304 {
305         struct kvm *kvm;
306         struct kvm_vcpu *vcpu;
307         unsigned long i;
308         unsigned long long *delta = v;
309
310         list_for_each_entry(kvm, &vm_list, vm_list) {
311                 kvm_for_each_vcpu(i, vcpu, kvm) {
312                         kvm_clock_sync_scb(vcpu->arch.sie_block, *delta);
313                         if (i == 0) {
314                                 kvm->arch.epoch = vcpu->arch.sie_block->epoch;
315                                 kvm->arch.epdx = vcpu->arch.sie_block->epdx;
316                         }
317                         if (vcpu->arch.cputm_enabled)
318                                 vcpu->arch.cputm_start += *delta;
319                         if (vcpu->arch.vsie_block)
320                                 kvm_clock_sync_scb(vcpu->arch.vsie_block,
321                                                    *delta);
322                 }
323         }
324         return NOTIFY_OK;
325 }
326
327 static struct notifier_block kvm_clock_notifier = {
328         .notifier_call = kvm_clock_sync,
329 };
330
331 int kvm_arch_hardware_setup(void *opaque)
332 {
333         gmap_notifier.notifier_call = kvm_gmap_notifier;
334         gmap_register_pte_notifier(&gmap_notifier);
335         vsie_gmap_notifier.notifier_call = kvm_s390_vsie_gmap_notifier;
336         gmap_register_pte_notifier(&vsie_gmap_notifier);
337         atomic_notifier_chain_register(&s390_epoch_delta_notifier,
338                                        &kvm_clock_notifier);
339         return 0;
340 }
341
342 void kvm_arch_hardware_unsetup(void)
343 {
344         gmap_unregister_pte_notifier(&gmap_notifier);
345         gmap_unregister_pte_notifier(&vsie_gmap_notifier);
346         atomic_notifier_chain_unregister(&s390_epoch_delta_notifier,
347                                          &kvm_clock_notifier);
348 }
349
350 static void allow_cpu_feat(unsigned long nr)
351 {
352         set_bit_inv(nr, kvm_s390_available_cpu_feat);
353 }
354
355 static inline int plo_test_bit(unsigned char nr)
356 {
357         unsigned long function = (unsigned long)nr | 0x100;
358         int cc;
359
360         asm volatile(
361                 "       lgr     0,%[function]\n"
362                 /* Parameter registers are ignored for "test bit" */
363                 "       plo     0,0,0,0(0)\n"
364                 "       ipm     %0\n"
365                 "       srl     %0,28\n"
366                 : "=d" (cc)
367                 : [function] "d" (function)
368                 : "cc", "0");
369         return cc == 0;
370 }
371
372 static __always_inline void __insn32_query(unsigned int opcode, u8 *query)
373 {
374         asm volatile(
375                 "       lghi    0,0\n"
376                 "       lgr     1,%[query]\n"
377                 /* Parameter registers are ignored */
378                 "       .insn   rrf,%[opc] << 16,2,4,6,0\n"
379                 :
380                 : [query] "d" ((unsigned long)query), [opc] "i" (opcode)
381                 : "cc", "memory", "0", "1");
382 }
383
384 #define INSN_SORTL 0xb938
385 #define INSN_DFLTCC 0xb939
386
387 static void kvm_s390_cpu_feat_init(void)
388 {
389         int i;
390
391         for (i = 0; i < 256; ++i) {
392                 if (plo_test_bit(i))
393                         kvm_s390_available_subfunc.plo[i >> 3] |= 0x80 >> (i & 7);
394         }
395
396         if (test_facility(28)) /* TOD-clock steering */
397                 ptff(kvm_s390_available_subfunc.ptff,
398                      sizeof(kvm_s390_available_subfunc.ptff),
399                      PTFF_QAF);
400
401         if (test_facility(17)) { /* MSA */
402                 __cpacf_query(CPACF_KMAC, (cpacf_mask_t *)
403                               kvm_s390_available_subfunc.kmac);
404                 __cpacf_query(CPACF_KMC, (cpacf_mask_t *)
405                               kvm_s390_available_subfunc.kmc);
406                 __cpacf_query(CPACF_KM, (cpacf_mask_t *)
407                               kvm_s390_available_subfunc.km);
408                 __cpacf_query(CPACF_KIMD, (cpacf_mask_t *)
409                               kvm_s390_available_subfunc.kimd);
410                 __cpacf_query(CPACF_KLMD, (cpacf_mask_t *)
411                               kvm_s390_available_subfunc.klmd);
412         }
413         if (test_facility(76)) /* MSA3 */
414                 __cpacf_query(CPACF_PCKMO, (cpacf_mask_t *)
415                               kvm_s390_available_subfunc.pckmo);
416         if (test_facility(77)) { /* MSA4 */
417                 __cpacf_query(CPACF_KMCTR, (cpacf_mask_t *)
418                               kvm_s390_available_subfunc.kmctr);
419                 __cpacf_query(CPACF_KMF, (cpacf_mask_t *)
420                               kvm_s390_available_subfunc.kmf);
421                 __cpacf_query(CPACF_KMO, (cpacf_mask_t *)
422                               kvm_s390_available_subfunc.kmo);
423                 __cpacf_query(CPACF_PCC, (cpacf_mask_t *)
424                               kvm_s390_available_subfunc.pcc);
425         }
426         if (test_facility(57)) /* MSA5 */
427                 __cpacf_query(CPACF_PRNO, (cpacf_mask_t *)
428                               kvm_s390_available_subfunc.ppno);
429
430         if (test_facility(146)) /* MSA8 */
431                 __cpacf_query(CPACF_KMA, (cpacf_mask_t *)
432                               kvm_s390_available_subfunc.kma);
433
434         if (test_facility(155)) /* MSA9 */
435                 __cpacf_query(CPACF_KDSA, (cpacf_mask_t *)
436                               kvm_s390_available_subfunc.kdsa);
437
438         if (test_facility(150)) /* SORTL */
439                 __insn32_query(INSN_SORTL, kvm_s390_available_subfunc.sortl);
440
441         if (test_facility(151)) /* DFLTCC */
442                 __insn32_query(INSN_DFLTCC, kvm_s390_available_subfunc.dfltcc);
443
444         if (MACHINE_HAS_ESOP)
445                 allow_cpu_feat(KVM_S390_VM_CPU_FEAT_ESOP);
446         /*
447          * We need SIE support, ESOP (PROT_READ protection for gmap_shadow),
448          * 64bit SCAO (SCA passthrough) and IDTE (for gmap_shadow unshadowing).
449          */
450         if (!sclp.has_sief2 || !MACHINE_HAS_ESOP || !sclp.has_64bscao ||
451             !test_facility(3) || !nested)
452                 return;
453         allow_cpu_feat(KVM_S390_VM_CPU_FEAT_SIEF2);
454         if (sclp.has_64bscao)
455                 allow_cpu_feat(KVM_S390_VM_CPU_FEAT_64BSCAO);
456         if (sclp.has_siif)
457                 allow_cpu_feat(KVM_S390_VM_CPU_FEAT_SIIF);
458         if (sclp.has_gpere)
459                 allow_cpu_feat(KVM_S390_VM_CPU_FEAT_GPERE);
460         if (sclp.has_gsls)
461                 allow_cpu_feat(KVM_S390_VM_CPU_FEAT_GSLS);
462         if (sclp.has_ib)
463                 allow_cpu_feat(KVM_S390_VM_CPU_FEAT_IB);
464         if (sclp.has_cei)
465                 allow_cpu_feat(KVM_S390_VM_CPU_FEAT_CEI);
466         if (sclp.has_ibs)
467                 allow_cpu_feat(KVM_S390_VM_CPU_FEAT_IBS);
468         if (sclp.has_kss)
469                 allow_cpu_feat(KVM_S390_VM_CPU_FEAT_KSS);
470         /*
471          * KVM_S390_VM_CPU_FEAT_SKEY: Wrong shadow of PTE.I bits will make
472          * all skey handling functions read/set the skey from the PGSTE
473          * instead of the real storage key.
474          *
475          * KVM_S390_VM_CPU_FEAT_CMMA: Wrong shadow of PTE.I bits will make
476          * pages being detected as preserved although they are resident.
477          *
478          * KVM_S390_VM_CPU_FEAT_PFMFI: Wrong shadow of PTE.I bits will
479          * have the same effect as for KVM_S390_VM_CPU_FEAT_SKEY.
480          *
481          * For KVM_S390_VM_CPU_FEAT_SKEY, KVM_S390_VM_CPU_FEAT_CMMA and
482          * KVM_S390_VM_CPU_FEAT_PFMFI, all PTE.I and PGSTE bits have to be
483          * correctly shadowed. We can do that for the PGSTE but not for PTE.I.
484          *
485          * KVM_S390_VM_CPU_FEAT_SIGPIF: Wrong SCB addresses in the SCA. We
486          * cannot easily shadow the SCA because of the ipte lock.
487          */
488 }
489
490 int kvm_arch_init(void *opaque)
491 {
492         int rc = -ENOMEM;
493
494         kvm_s390_dbf = debug_register("kvm-trace", 32, 1, 7 * sizeof(long));
495         if (!kvm_s390_dbf)
496                 return -ENOMEM;
497
498         kvm_s390_dbf_uv = debug_register("kvm-uv", 32, 1, 7 * sizeof(long));
499         if (!kvm_s390_dbf_uv)
500                 goto out;
501
502         if (debug_register_view(kvm_s390_dbf, &debug_sprintf_view) ||
503             debug_register_view(kvm_s390_dbf_uv, &debug_sprintf_view))
504                 goto out;
505
506         kvm_s390_cpu_feat_init();
507
508         /* Register floating interrupt controller interface. */
509         rc = kvm_register_device_ops(&kvm_flic_ops, KVM_DEV_TYPE_FLIC);
510         if (rc) {
511                 pr_err("A FLIC registration call failed with rc=%d\n", rc);
512                 goto out;
513         }
514
515         if (IS_ENABLED(CONFIG_VFIO_PCI_ZDEV_KVM)) {
516                 rc = kvm_s390_pci_init();
517                 if (rc) {
518                         pr_err("Unable to allocate AIFT for PCI\n");
519                         goto out;
520                 }
521         }
522
523         rc = kvm_s390_gib_init(GAL_ISC);
524         if (rc)
525                 goto out;
526
527         return 0;
528
529 out:
530         kvm_arch_exit();
531         return rc;
532 }
533
534 void kvm_arch_exit(void)
535 {
536         kvm_s390_gib_destroy();
537         if (IS_ENABLED(CONFIG_VFIO_PCI_ZDEV_KVM))
538                 kvm_s390_pci_exit();
539         debug_unregister(kvm_s390_dbf);
540         debug_unregister(kvm_s390_dbf_uv);
541 }
542
543 /* Section: device related */
544 long kvm_arch_dev_ioctl(struct file *filp,
545                         unsigned int ioctl, unsigned long arg)
546 {
547         if (ioctl == KVM_S390_ENABLE_SIE)
548                 return s390_enable_sie();
549         return -EINVAL;
550 }
551
552 int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
553 {
554         int r;
555
556         switch (ext) {
557         case KVM_CAP_S390_PSW:
558         case KVM_CAP_S390_GMAP:
559         case KVM_CAP_SYNC_MMU:
560 #ifdef CONFIG_KVM_S390_UCONTROL
561         case KVM_CAP_S390_UCONTROL:
562 #endif
563         case KVM_CAP_ASYNC_PF:
564         case KVM_CAP_SYNC_REGS:
565         case KVM_CAP_ONE_REG:
566         case KVM_CAP_ENABLE_CAP:
567         case KVM_CAP_S390_CSS_SUPPORT:
568         case KVM_CAP_IOEVENTFD:
569         case KVM_CAP_DEVICE_CTRL:
570         case KVM_CAP_S390_IRQCHIP:
571         case KVM_CAP_VM_ATTRIBUTES:
572         case KVM_CAP_MP_STATE:
573         case KVM_CAP_IMMEDIATE_EXIT:
574         case KVM_CAP_S390_INJECT_IRQ:
575         case KVM_CAP_S390_USER_SIGP:
576         case KVM_CAP_S390_USER_STSI:
577         case KVM_CAP_S390_SKEYS:
578         case KVM_CAP_S390_IRQ_STATE:
579         case KVM_CAP_S390_USER_INSTR0:
580         case KVM_CAP_S390_CMMA_MIGRATION:
581         case KVM_CAP_S390_AIS:
582         case KVM_CAP_S390_AIS_MIGRATION:
583         case KVM_CAP_S390_VCPU_RESETS:
584         case KVM_CAP_SET_GUEST_DEBUG:
585         case KVM_CAP_S390_DIAG318:
586         case KVM_CAP_S390_MEM_OP_EXTENSION:
587                 r = 1;
588                 break;
589         case KVM_CAP_SET_GUEST_DEBUG2:
590                 r = KVM_GUESTDBG_VALID_MASK;
591                 break;
592         case KVM_CAP_S390_HPAGE_1M:
593                 r = 0;
594                 if (hpage && !kvm_is_ucontrol(kvm))
595                         r = 1;
596                 break;
597         case KVM_CAP_S390_MEM_OP:
598                 r = MEM_OP_MAX_SIZE;
599                 break;
600         case KVM_CAP_NR_VCPUS:
601         case KVM_CAP_MAX_VCPUS:
602         case KVM_CAP_MAX_VCPU_ID:
603                 r = KVM_S390_BSCA_CPU_SLOTS;
604                 if (!kvm_s390_use_sca_entries())
605                         r = KVM_MAX_VCPUS;
606                 else if (sclp.has_esca && sclp.has_64bscao)
607                         r = KVM_S390_ESCA_CPU_SLOTS;
608                 if (ext == KVM_CAP_NR_VCPUS)
609                         r = min_t(unsigned int, num_online_cpus(), r);
610                 break;
611         case KVM_CAP_S390_COW:
612                 r = MACHINE_HAS_ESOP;
613                 break;
614         case KVM_CAP_S390_VECTOR_REGISTERS:
615                 r = MACHINE_HAS_VX;
616                 break;
617         case KVM_CAP_S390_RI:
618                 r = test_facility(64);
619                 break;
620         case KVM_CAP_S390_GS:
621                 r = test_facility(133);
622                 break;
623         case KVM_CAP_S390_BPB:
624                 r = test_facility(82);
625                 break;
626         case KVM_CAP_S390_PROTECTED:
627                 r = is_prot_virt_host();
628                 break;
629         case KVM_CAP_S390_PROTECTED_DUMP: {
630                 u64 pv_cmds_dump[] = {
631                         BIT_UVC_CMD_DUMP_INIT,
632                         BIT_UVC_CMD_DUMP_CONFIG_STOR_STATE,
633                         BIT_UVC_CMD_DUMP_CPU,
634                         BIT_UVC_CMD_DUMP_COMPLETE,
635                 };
636                 int i;
637
638                 r = is_prot_virt_host();
639
640                 for (i = 0; i < ARRAY_SIZE(pv_cmds_dump); i++) {
641                         if (!test_bit_inv(pv_cmds_dump[i],
642                                           (unsigned long *)&uv_info.inst_calls_list)) {
643                                 r = 0;
644                                 break;
645                         }
646                 }
647                 break;
648         }
649         case KVM_CAP_S390_ZPCI_OP:
650                 r = kvm_s390_pci_interp_allowed();
651                 break;
652         case KVM_CAP_S390_CPU_TOPOLOGY:
653                 r = test_facility(11);
654                 break;
655         default:
656                 r = 0;
657         }
658         return r;
659 }
660
661 void kvm_arch_sync_dirty_log(struct kvm *kvm, struct kvm_memory_slot *memslot)
662 {
663         int i;
664         gfn_t cur_gfn, last_gfn;
665         unsigned long gaddr, vmaddr;
666         struct gmap *gmap = kvm->arch.gmap;
667         DECLARE_BITMAP(bitmap, _PAGE_ENTRIES);
668
669         /* Loop over all guest segments */
670         cur_gfn = memslot->base_gfn;
671         last_gfn = memslot->base_gfn + memslot->npages;
672         for (; cur_gfn <= last_gfn; cur_gfn += _PAGE_ENTRIES) {
673                 gaddr = gfn_to_gpa(cur_gfn);
674                 vmaddr = gfn_to_hva_memslot(memslot, cur_gfn);
675                 if (kvm_is_error_hva(vmaddr))
676                         continue;
677
678                 bitmap_zero(bitmap, _PAGE_ENTRIES);
679                 gmap_sync_dirty_log_pmd(gmap, bitmap, gaddr, vmaddr);
680                 for (i = 0; i < _PAGE_ENTRIES; i++) {
681                         if (test_bit(i, bitmap))
682                                 mark_page_dirty(kvm, cur_gfn + i);
683                 }
684
685                 if (fatal_signal_pending(current))
686                         return;
687                 cond_resched();
688         }
689 }
690
691 /* Section: vm related */
692 static void sca_del_vcpu(struct kvm_vcpu *vcpu);
693
694 /*
695  * Get (and clear) the dirty memory log for a memory slot.
696  */
697 int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm,
698                                struct kvm_dirty_log *log)
699 {
700         int r;
701         unsigned long n;
702         struct kvm_memory_slot *memslot;
703         int is_dirty;
704
705         if (kvm_is_ucontrol(kvm))
706                 return -EINVAL;
707
708         mutex_lock(&kvm->slots_lock);
709
710         r = -EINVAL;
711         if (log->slot >= KVM_USER_MEM_SLOTS)
712                 goto out;
713
714         r = kvm_get_dirty_log(kvm, log, &is_dirty, &memslot);
715         if (r)
716                 goto out;
717
718         /* Clear the dirty log */
719         if (is_dirty) {
720                 n = kvm_dirty_bitmap_bytes(memslot);
721                 memset(memslot->dirty_bitmap, 0, n);
722         }
723         r = 0;
724 out:
725         mutex_unlock(&kvm->slots_lock);
726         return r;
727 }
728
729 static void icpt_operexc_on_all_vcpus(struct kvm *kvm)
730 {
731         unsigned long i;
732         struct kvm_vcpu *vcpu;
733
734         kvm_for_each_vcpu(i, vcpu, kvm) {
735                 kvm_s390_sync_request(KVM_REQ_ICPT_OPEREXC, vcpu);
736         }
737 }
738
739 int kvm_vm_ioctl_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap)
740 {
741         int r;
742
743         if (cap->flags)
744                 return -EINVAL;
745
746         switch (cap->cap) {
747         case KVM_CAP_S390_IRQCHIP:
748                 VM_EVENT(kvm, 3, "%s", "ENABLE: CAP_S390_IRQCHIP");
749                 kvm->arch.use_irqchip = 1;
750                 r = 0;
751                 break;
752         case KVM_CAP_S390_USER_SIGP:
753                 VM_EVENT(kvm, 3, "%s", "ENABLE: CAP_S390_USER_SIGP");
754                 kvm->arch.user_sigp = 1;
755                 r = 0;
756                 break;
757         case KVM_CAP_S390_VECTOR_REGISTERS:
758                 mutex_lock(&kvm->lock);
759                 if (kvm->created_vcpus) {
760                         r = -EBUSY;
761                 } else if (MACHINE_HAS_VX) {
762                         set_kvm_facility(kvm->arch.model.fac_mask, 129);
763                         set_kvm_facility(kvm->arch.model.fac_list, 129);
764                         if (test_facility(134)) {
765                                 set_kvm_facility(kvm->arch.model.fac_mask, 134);
766                                 set_kvm_facility(kvm->arch.model.fac_list, 134);
767                         }
768                         if (test_facility(135)) {
769                                 set_kvm_facility(kvm->arch.model.fac_mask, 135);
770                                 set_kvm_facility(kvm->arch.model.fac_list, 135);
771                         }
772                         if (test_facility(148)) {
773                                 set_kvm_facility(kvm->arch.model.fac_mask, 148);
774                                 set_kvm_facility(kvm->arch.model.fac_list, 148);
775                         }
776                         if (test_facility(152)) {
777                                 set_kvm_facility(kvm->arch.model.fac_mask, 152);
778                                 set_kvm_facility(kvm->arch.model.fac_list, 152);
779                         }
780                         if (test_facility(192)) {
781                                 set_kvm_facility(kvm->arch.model.fac_mask, 192);
782                                 set_kvm_facility(kvm->arch.model.fac_list, 192);
783                         }
784                         r = 0;
785                 } else
786                         r = -EINVAL;
787                 mutex_unlock(&kvm->lock);
788                 VM_EVENT(kvm, 3, "ENABLE: CAP_S390_VECTOR_REGISTERS %s",
789                          r ? "(not available)" : "(success)");
790                 break;
791         case KVM_CAP_S390_RI:
792                 r = -EINVAL;
793                 mutex_lock(&kvm->lock);
794                 if (kvm->created_vcpus) {
795                         r = -EBUSY;
796                 } else if (test_facility(64)) {
797                         set_kvm_facility(kvm->arch.model.fac_mask, 64);
798                         set_kvm_facility(kvm->arch.model.fac_list, 64);
799                         r = 0;
800                 }
801                 mutex_unlock(&kvm->lock);
802                 VM_EVENT(kvm, 3, "ENABLE: CAP_S390_RI %s",
803                          r ? "(not available)" : "(success)");
804                 break;
805         case KVM_CAP_S390_AIS:
806                 mutex_lock(&kvm->lock);
807                 if (kvm->created_vcpus) {
808                         r = -EBUSY;
809                 } else {
810                         set_kvm_facility(kvm->arch.model.fac_mask, 72);
811                         set_kvm_facility(kvm->arch.model.fac_list, 72);
812                         r = 0;
813                 }
814                 mutex_unlock(&kvm->lock);
815                 VM_EVENT(kvm, 3, "ENABLE: AIS %s",
816                          r ? "(not available)" : "(success)");
817                 break;
818         case KVM_CAP_S390_GS:
819                 r = -EINVAL;
820                 mutex_lock(&kvm->lock);
821                 if (kvm->created_vcpus) {
822                         r = -EBUSY;
823                 } else if (test_facility(133)) {
824                         set_kvm_facility(kvm->arch.model.fac_mask, 133);
825                         set_kvm_facility(kvm->arch.model.fac_list, 133);
826                         r = 0;
827                 }
828                 mutex_unlock(&kvm->lock);
829                 VM_EVENT(kvm, 3, "ENABLE: CAP_S390_GS %s",
830                          r ? "(not available)" : "(success)");
831                 break;
832         case KVM_CAP_S390_HPAGE_1M:
833                 mutex_lock(&kvm->lock);
834                 if (kvm->created_vcpus)
835                         r = -EBUSY;
836                 else if (!hpage || kvm->arch.use_cmma || kvm_is_ucontrol(kvm))
837                         r = -EINVAL;
838                 else {
839                         r = 0;
840                         mmap_write_lock(kvm->mm);
841                         kvm->mm->context.allow_gmap_hpage_1m = 1;
842                         mmap_write_unlock(kvm->mm);
843                         /*
844                          * We might have to create fake 4k page
845                          * tables. To avoid that the hardware works on
846                          * stale PGSTEs, we emulate these instructions.
847                          */
848                         kvm->arch.use_skf = 0;
849                         kvm->arch.use_pfmfi = 0;
850                 }
851                 mutex_unlock(&kvm->lock);
852                 VM_EVENT(kvm, 3, "ENABLE: CAP_S390_HPAGE %s",
853                          r ? "(not available)" : "(success)");
854                 break;
855         case KVM_CAP_S390_USER_STSI:
856                 VM_EVENT(kvm, 3, "%s", "ENABLE: CAP_S390_USER_STSI");
857                 kvm->arch.user_stsi = 1;
858                 r = 0;
859                 break;
860         case KVM_CAP_S390_USER_INSTR0:
861                 VM_EVENT(kvm, 3, "%s", "ENABLE: CAP_S390_USER_INSTR0");
862                 kvm->arch.user_instr0 = 1;
863                 icpt_operexc_on_all_vcpus(kvm);
864                 r = 0;
865                 break;
866         case KVM_CAP_S390_CPU_TOPOLOGY:
867                 r = -EINVAL;
868                 mutex_lock(&kvm->lock);
869                 if (kvm->created_vcpus) {
870                         r = -EBUSY;
871                 } else if (test_facility(11)) {
872                         set_kvm_facility(kvm->arch.model.fac_mask, 11);
873                         set_kvm_facility(kvm->arch.model.fac_list, 11);
874                         r = 0;
875                 }
876                 mutex_unlock(&kvm->lock);
877                 VM_EVENT(kvm, 3, "ENABLE: CAP_S390_CPU_TOPOLOGY %s",
878                          r ? "(not available)" : "(success)");
879                 break;
880         default:
881                 r = -EINVAL;
882                 break;
883         }
884         return r;
885 }
886
887 static int kvm_s390_get_mem_control(struct kvm *kvm, struct kvm_device_attr *attr)
888 {
889         int ret;
890
891         switch (attr->attr) {
892         case KVM_S390_VM_MEM_LIMIT_SIZE:
893                 ret = 0;
894                 VM_EVENT(kvm, 3, "QUERY: max guest memory: %lu bytes",
895                          kvm->arch.mem_limit);
896                 if (put_user(kvm->arch.mem_limit, (u64 __user *)attr->addr))
897                         ret = -EFAULT;
898                 break;
899         default:
900                 ret = -ENXIO;
901                 break;
902         }
903         return ret;
904 }
905
906 static int kvm_s390_set_mem_control(struct kvm *kvm, struct kvm_device_attr *attr)
907 {
908         int ret;
909         unsigned int idx;
910         switch (attr->attr) {
911         case KVM_S390_VM_MEM_ENABLE_CMMA:
912                 ret = -ENXIO;
913                 if (!sclp.has_cmma)
914                         break;
915
916                 VM_EVENT(kvm, 3, "%s", "ENABLE: CMMA support");
917                 mutex_lock(&kvm->lock);
918                 if (kvm->created_vcpus)
919                         ret = -EBUSY;
920                 else if (kvm->mm->context.allow_gmap_hpage_1m)
921                         ret = -EINVAL;
922                 else {
923                         kvm->arch.use_cmma = 1;
924                         /* Not compatible with cmma. */
925                         kvm->arch.use_pfmfi = 0;
926                         ret = 0;
927                 }
928                 mutex_unlock(&kvm->lock);
929                 break;
930         case KVM_S390_VM_MEM_CLR_CMMA:
931                 ret = -ENXIO;
932                 if (!sclp.has_cmma)
933                         break;
934                 ret = -EINVAL;
935                 if (!kvm->arch.use_cmma)
936                         break;
937
938                 VM_EVENT(kvm, 3, "%s", "RESET: CMMA states");
939                 mutex_lock(&kvm->lock);
940                 idx = srcu_read_lock(&kvm->srcu);
941                 s390_reset_cmma(kvm->arch.gmap->mm);
942                 srcu_read_unlock(&kvm->srcu, idx);
943                 mutex_unlock(&kvm->lock);
944                 ret = 0;
945                 break;
946         case KVM_S390_VM_MEM_LIMIT_SIZE: {
947                 unsigned long new_limit;
948
949                 if (kvm_is_ucontrol(kvm))
950                         return -EINVAL;
951
952                 if (get_user(new_limit, (u64 __user *)attr->addr))
953                         return -EFAULT;
954
955                 if (kvm->arch.mem_limit != KVM_S390_NO_MEM_LIMIT &&
956                     new_limit > kvm->arch.mem_limit)
957                         return -E2BIG;
958
959                 if (!new_limit)
960                         return -EINVAL;
961
962                 /* gmap_create takes last usable address */
963                 if (new_limit != KVM_S390_NO_MEM_LIMIT)
964                         new_limit -= 1;
965
966                 ret = -EBUSY;
967                 mutex_lock(&kvm->lock);
968                 if (!kvm->created_vcpus) {
969                         /* gmap_create will round the limit up */
970                         struct gmap *new = gmap_create(current->mm, new_limit);
971
972                         if (!new) {
973                                 ret = -ENOMEM;
974                         } else {
975                                 gmap_remove(kvm->arch.gmap);
976                                 new->private = kvm;
977                                 kvm->arch.gmap = new;
978                                 ret = 0;
979                         }
980                 }
981                 mutex_unlock(&kvm->lock);
982                 VM_EVENT(kvm, 3, "SET: max guest address: %lu", new_limit);
983                 VM_EVENT(kvm, 3, "New guest asce: 0x%pK",
984                          (void *) kvm->arch.gmap->asce);
985                 break;
986         }
987         default:
988                 ret = -ENXIO;
989                 break;
990         }
991         return ret;
992 }
993
994 static void kvm_s390_vcpu_crypto_setup(struct kvm_vcpu *vcpu);
995
996 void kvm_s390_vcpu_crypto_reset_all(struct kvm *kvm)
997 {
998         struct kvm_vcpu *vcpu;
999         unsigned long i;
1000
1001         kvm_s390_vcpu_block_all(kvm);
1002
1003         kvm_for_each_vcpu(i, vcpu, kvm) {
1004                 kvm_s390_vcpu_crypto_setup(vcpu);
1005                 /* recreate the shadow crycb by leaving the VSIE handler */
1006                 kvm_s390_sync_request(KVM_REQ_VSIE_RESTART, vcpu);
1007         }
1008
1009         kvm_s390_vcpu_unblock_all(kvm);
1010 }
1011
1012 static int kvm_s390_vm_set_crypto(struct kvm *kvm, struct kvm_device_attr *attr)
1013 {
1014         mutex_lock(&kvm->lock);
1015         switch (attr->attr) {
1016         case KVM_S390_VM_CRYPTO_ENABLE_AES_KW:
1017                 if (!test_kvm_facility(kvm, 76)) {
1018                         mutex_unlock(&kvm->lock);
1019                         return -EINVAL;
1020                 }
1021                 get_random_bytes(
1022                         kvm->arch.crypto.crycb->aes_wrapping_key_mask,
1023                         sizeof(kvm->arch.crypto.crycb->aes_wrapping_key_mask));
1024                 kvm->arch.crypto.aes_kw = 1;
1025                 VM_EVENT(kvm, 3, "%s", "ENABLE: AES keywrapping support");
1026                 break;
1027         case KVM_S390_VM_CRYPTO_ENABLE_DEA_KW:
1028                 if (!test_kvm_facility(kvm, 76)) {
1029                         mutex_unlock(&kvm->lock);
1030                         return -EINVAL;
1031                 }
1032                 get_random_bytes(
1033                         kvm->arch.crypto.crycb->dea_wrapping_key_mask,
1034                         sizeof(kvm->arch.crypto.crycb->dea_wrapping_key_mask));
1035                 kvm->arch.crypto.dea_kw = 1;
1036                 VM_EVENT(kvm, 3, "%s", "ENABLE: DEA keywrapping support");
1037                 break;
1038         case KVM_S390_VM_CRYPTO_DISABLE_AES_KW:
1039                 if (!test_kvm_facility(kvm, 76)) {
1040                         mutex_unlock(&kvm->lock);
1041                         return -EINVAL;
1042                 }
1043                 kvm->arch.crypto.aes_kw = 0;
1044                 memset(kvm->arch.crypto.crycb->aes_wrapping_key_mask, 0,
1045                         sizeof(kvm->arch.crypto.crycb->aes_wrapping_key_mask));
1046                 VM_EVENT(kvm, 3, "%s", "DISABLE: AES keywrapping support");
1047                 break;
1048         case KVM_S390_VM_CRYPTO_DISABLE_DEA_KW:
1049                 if (!test_kvm_facility(kvm, 76)) {
1050                         mutex_unlock(&kvm->lock);
1051                         return -EINVAL;
1052                 }
1053                 kvm->arch.crypto.dea_kw = 0;
1054                 memset(kvm->arch.crypto.crycb->dea_wrapping_key_mask, 0,
1055                         sizeof(kvm->arch.crypto.crycb->dea_wrapping_key_mask));
1056                 VM_EVENT(kvm, 3, "%s", "DISABLE: DEA keywrapping support");
1057                 break;
1058         case KVM_S390_VM_CRYPTO_ENABLE_APIE:
1059                 if (!ap_instructions_available()) {
1060                         mutex_unlock(&kvm->lock);
1061                         return -EOPNOTSUPP;
1062                 }
1063                 kvm->arch.crypto.apie = 1;
1064                 break;
1065         case KVM_S390_VM_CRYPTO_DISABLE_APIE:
1066                 if (!ap_instructions_available()) {
1067                         mutex_unlock(&kvm->lock);
1068                         return -EOPNOTSUPP;
1069                 }
1070                 kvm->arch.crypto.apie = 0;
1071                 break;
1072         default:
1073                 mutex_unlock(&kvm->lock);
1074                 return -ENXIO;
1075         }
1076
1077         kvm_s390_vcpu_crypto_reset_all(kvm);
1078         mutex_unlock(&kvm->lock);
1079         return 0;
1080 }
1081
1082 static void kvm_s390_vcpu_pci_setup(struct kvm_vcpu *vcpu)
1083 {
1084         /* Only set the ECB bits after guest requests zPCI interpretation */
1085         if (!vcpu->kvm->arch.use_zpci_interp)
1086                 return;
1087
1088         vcpu->arch.sie_block->ecb2 |= ECB2_ZPCI_LSI;
1089         vcpu->arch.sie_block->ecb3 |= ECB3_AISII + ECB3_AISI;
1090 }
1091
1092 void kvm_s390_vcpu_pci_enable_interp(struct kvm *kvm)
1093 {
1094         struct kvm_vcpu *vcpu;
1095         unsigned long i;
1096
1097         lockdep_assert_held(&kvm->lock);
1098
1099         if (!kvm_s390_pci_interp_allowed())
1100                 return;
1101
1102         /*
1103          * If host is configured for PCI and the necessary facilities are
1104          * available, turn on interpretation for the life of this guest
1105          */
1106         kvm->arch.use_zpci_interp = 1;
1107
1108         kvm_s390_vcpu_block_all(kvm);
1109
1110         kvm_for_each_vcpu(i, vcpu, kvm) {
1111                 kvm_s390_vcpu_pci_setup(vcpu);
1112                 kvm_s390_sync_request(KVM_REQ_VSIE_RESTART, vcpu);
1113         }
1114
1115         kvm_s390_vcpu_unblock_all(kvm);
1116 }
1117
1118 static void kvm_s390_sync_request_broadcast(struct kvm *kvm, int req)
1119 {
1120         unsigned long cx;
1121         struct kvm_vcpu *vcpu;
1122
1123         kvm_for_each_vcpu(cx, vcpu, kvm)
1124                 kvm_s390_sync_request(req, vcpu);
1125 }
1126
1127 /*
1128  * Must be called with kvm->srcu held to avoid races on memslots, and with
1129  * kvm->slots_lock to avoid races with ourselves and kvm_s390_vm_stop_migration.
1130  */
1131 static int kvm_s390_vm_start_migration(struct kvm *kvm)
1132 {
1133         struct kvm_memory_slot *ms;
1134         struct kvm_memslots *slots;
1135         unsigned long ram_pages = 0;
1136         int bkt;
1137
1138         /* migration mode already enabled */
1139         if (kvm->arch.migration_mode)
1140                 return 0;
1141         slots = kvm_memslots(kvm);
1142         if (!slots || kvm_memslots_empty(slots))
1143                 return -EINVAL;
1144
1145         if (!kvm->arch.use_cmma) {
1146                 kvm->arch.migration_mode = 1;
1147                 return 0;
1148         }
1149         /* mark all the pages in active slots as dirty */
1150         kvm_for_each_memslot(ms, bkt, slots) {
1151                 if (!ms->dirty_bitmap)
1152                         return -EINVAL;
1153                 /*
1154                  * The second half of the bitmap is only used on x86,
1155                  * and would be wasted otherwise, so we put it to good
1156                  * use here to keep track of the state of the storage
1157                  * attributes.
1158                  */
1159                 memset(kvm_second_dirty_bitmap(ms), 0xff, kvm_dirty_bitmap_bytes(ms));
1160                 ram_pages += ms->npages;
1161         }
1162         atomic64_set(&kvm->arch.cmma_dirty_pages, ram_pages);
1163         kvm->arch.migration_mode = 1;
1164         kvm_s390_sync_request_broadcast(kvm, KVM_REQ_START_MIGRATION);
1165         return 0;
1166 }
1167
1168 /*
1169  * Must be called with kvm->slots_lock to avoid races with ourselves and
1170  * kvm_s390_vm_start_migration.
1171  */
1172 static int kvm_s390_vm_stop_migration(struct kvm *kvm)
1173 {
1174         /* migration mode already disabled */
1175         if (!kvm->arch.migration_mode)
1176                 return 0;
1177         kvm->arch.migration_mode = 0;
1178         if (kvm->arch.use_cmma)
1179                 kvm_s390_sync_request_broadcast(kvm, KVM_REQ_STOP_MIGRATION);
1180         return 0;
1181 }
1182
1183 static int kvm_s390_vm_set_migration(struct kvm *kvm,
1184                                      struct kvm_device_attr *attr)
1185 {
1186         int res = -ENXIO;
1187
1188         mutex_lock(&kvm->slots_lock);
1189         switch (attr->attr) {
1190         case KVM_S390_VM_MIGRATION_START:
1191                 res = kvm_s390_vm_start_migration(kvm);
1192                 break;
1193         case KVM_S390_VM_MIGRATION_STOP:
1194                 res = kvm_s390_vm_stop_migration(kvm);
1195                 break;
1196         default:
1197                 break;
1198         }
1199         mutex_unlock(&kvm->slots_lock);
1200
1201         return res;
1202 }
1203
1204 static int kvm_s390_vm_get_migration(struct kvm *kvm,
1205                                      struct kvm_device_attr *attr)
1206 {
1207         u64 mig = kvm->arch.migration_mode;
1208
1209         if (attr->attr != KVM_S390_VM_MIGRATION_STATUS)
1210                 return -ENXIO;
1211
1212         if (copy_to_user((void __user *)attr->addr, &mig, sizeof(mig)))
1213                 return -EFAULT;
1214         return 0;
1215 }
1216
1217 static void __kvm_s390_set_tod_clock(struct kvm *kvm, const struct kvm_s390_vm_tod_clock *gtod);
1218
1219 static int kvm_s390_set_tod_ext(struct kvm *kvm, struct kvm_device_attr *attr)
1220 {
1221         struct kvm_s390_vm_tod_clock gtod;
1222
1223         if (copy_from_user(&gtod, (void __user *)attr->addr, sizeof(gtod)))
1224                 return -EFAULT;
1225
1226         if (!test_kvm_facility(kvm, 139) && gtod.epoch_idx)
1227                 return -EINVAL;
1228         __kvm_s390_set_tod_clock(kvm, &gtod);
1229
1230         VM_EVENT(kvm, 3, "SET: TOD extension: 0x%x, TOD base: 0x%llx",
1231                 gtod.epoch_idx, gtod.tod);
1232
1233         return 0;
1234 }
1235
1236 static int kvm_s390_set_tod_high(struct kvm *kvm, struct kvm_device_attr *attr)
1237 {
1238         u8 gtod_high;
1239
1240         if (copy_from_user(&gtod_high, (void __user *)attr->addr,
1241                                            sizeof(gtod_high)))
1242                 return -EFAULT;
1243
1244         if (gtod_high != 0)
1245                 return -EINVAL;
1246         VM_EVENT(kvm, 3, "SET: TOD extension: 0x%x", gtod_high);
1247
1248         return 0;
1249 }
1250
1251 static int kvm_s390_set_tod_low(struct kvm *kvm, struct kvm_device_attr *attr)
1252 {
1253         struct kvm_s390_vm_tod_clock gtod = { 0 };
1254
1255         if (copy_from_user(&gtod.tod, (void __user *)attr->addr,
1256                            sizeof(gtod.tod)))
1257                 return -EFAULT;
1258
1259         __kvm_s390_set_tod_clock(kvm, &gtod);
1260         VM_EVENT(kvm, 3, "SET: TOD base: 0x%llx", gtod.tod);
1261         return 0;
1262 }
1263
1264 static int kvm_s390_set_tod(struct kvm *kvm, struct kvm_device_attr *attr)
1265 {
1266         int ret;
1267
1268         if (attr->flags)
1269                 return -EINVAL;
1270
1271         mutex_lock(&kvm->lock);
1272         /*
1273          * For protected guests, the TOD is managed by the ultravisor, so trying
1274          * to change it will never bring the expected results.
1275          */
1276         if (kvm_s390_pv_is_protected(kvm)) {
1277                 ret = -EOPNOTSUPP;
1278                 goto out_unlock;
1279         }
1280
1281         switch (attr->attr) {
1282         case KVM_S390_VM_TOD_EXT:
1283                 ret = kvm_s390_set_tod_ext(kvm, attr);
1284                 break;
1285         case KVM_S390_VM_TOD_HIGH:
1286                 ret = kvm_s390_set_tod_high(kvm, attr);
1287                 break;
1288         case KVM_S390_VM_TOD_LOW:
1289                 ret = kvm_s390_set_tod_low(kvm, attr);
1290                 break;
1291         default:
1292                 ret = -ENXIO;
1293                 break;
1294         }
1295
1296 out_unlock:
1297         mutex_unlock(&kvm->lock);
1298         return ret;
1299 }
1300
1301 static void kvm_s390_get_tod_clock(struct kvm *kvm,
1302                                    struct kvm_s390_vm_tod_clock *gtod)
1303 {
1304         union tod_clock clk;
1305
1306         preempt_disable();
1307
1308         store_tod_clock_ext(&clk);
1309
1310         gtod->tod = clk.tod + kvm->arch.epoch;
1311         gtod->epoch_idx = 0;
1312         if (test_kvm_facility(kvm, 139)) {
1313                 gtod->epoch_idx = clk.ei + kvm->arch.epdx;
1314                 if (gtod->tod < clk.tod)
1315                         gtod->epoch_idx += 1;
1316         }
1317
1318         preempt_enable();
1319 }
1320
1321 static int kvm_s390_get_tod_ext(struct kvm *kvm, struct kvm_device_attr *attr)
1322 {
1323         struct kvm_s390_vm_tod_clock gtod;
1324
1325         memset(&gtod, 0, sizeof(gtod));
1326         kvm_s390_get_tod_clock(kvm, &gtod);
1327         if (copy_to_user((void __user *)attr->addr, &gtod, sizeof(gtod)))
1328                 return -EFAULT;
1329
1330         VM_EVENT(kvm, 3, "QUERY: TOD extension: 0x%x, TOD base: 0x%llx",
1331                 gtod.epoch_idx, gtod.tod);
1332         return 0;
1333 }
1334
1335 static int kvm_s390_get_tod_high(struct kvm *kvm, struct kvm_device_attr *attr)
1336 {
1337         u8 gtod_high = 0;
1338
1339         if (copy_to_user((void __user *)attr->addr, &gtod_high,
1340                                          sizeof(gtod_high)))
1341                 return -EFAULT;
1342         VM_EVENT(kvm, 3, "QUERY: TOD extension: 0x%x", gtod_high);
1343
1344         return 0;
1345 }
1346
1347 static int kvm_s390_get_tod_low(struct kvm *kvm, struct kvm_device_attr *attr)
1348 {
1349         u64 gtod;
1350
1351         gtod = kvm_s390_get_tod_clock_fast(kvm);
1352         if (copy_to_user((void __user *)attr->addr, &gtod, sizeof(gtod)))
1353                 return -EFAULT;
1354         VM_EVENT(kvm, 3, "QUERY: TOD base: 0x%llx", gtod);
1355
1356         return 0;
1357 }
1358
1359 static int kvm_s390_get_tod(struct kvm *kvm, struct kvm_device_attr *attr)
1360 {
1361         int ret;
1362
1363         if (attr->flags)
1364                 return -EINVAL;
1365
1366         switch (attr->attr) {
1367         case KVM_S390_VM_TOD_EXT:
1368                 ret = kvm_s390_get_tod_ext(kvm, attr);
1369                 break;
1370         case KVM_S390_VM_TOD_HIGH:
1371                 ret = kvm_s390_get_tod_high(kvm, attr);
1372                 break;
1373         case KVM_S390_VM_TOD_LOW:
1374                 ret = kvm_s390_get_tod_low(kvm, attr);
1375                 break;
1376         default:
1377                 ret = -ENXIO;
1378                 break;
1379         }
1380         return ret;
1381 }
1382
1383 static int kvm_s390_set_processor(struct kvm *kvm, struct kvm_device_attr *attr)
1384 {
1385         struct kvm_s390_vm_cpu_processor *proc;
1386         u16 lowest_ibc, unblocked_ibc;
1387         int ret = 0;
1388
1389         mutex_lock(&kvm->lock);
1390         if (kvm->created_vcpus) {
1391                 ret = -EBUSY;
1392                 goto out;
1393         }
1394         proc = kzalloc(sizeof(*proc), GFP_KERNEL_ACCOUNT);
1395         if (!proc) {
1396                 ret = -ENOMEM;
1397                 goto out;
1398         }
1399         if (!copy_from_user(proc, (void __user *)attr->addr,
1400                             sizeof(*proc))) {
1401                 kvm->arch.model.cpuid = proc->cpuid;
1402                 lowest_ibc = sclp.ibc >> 16 & 0xfff;
1403                 unblocked_ibc = sclp.ibc & 0xfff;
1404                 if (lowest_ibc && proc->ibc) {
1405                         if (proc->ibc > unblocked_ibc)
1406                                 kvm->arch.model.ibc = unblocked_ibc;
1407                         else if (proc->ibc < lowest_ibc)
1408                                 kvm->arch.model.ibc = lowest_ibc;
1409                         else
1410                                 kvm->arch.model.ibc = proc->ibc;
1411                 }
1412                 memcpy(kvm->arch.model.fac_list, proc->fac_list,
1413                        S390_ARCH_FAC_LIST_SIZE_BYTE);
1414                 VM_EVENT(kvm, 3, "SET: guest ibc: 0x%4.4x, guest cpuid: 0x%16.16llx",
1415                          kvm->arch.model.ibc,
1416                          kvm->arch.model.cpuid);
1417                 VM_EVENT(kvm, 3, "SET: guest faclist: 0x%16.16llx.%16.16llx.%16.16llx",
1418                          kvm->arch.model.fac_list[0],
1419                          kvm->arch.model.fac_list[1],
1420                          kvm->arch.model.fac_list[2]);
1421         } else
1422                 ret = -EFAULT;
1423         kfree(proc);
1424 out:
1425         mutex_unlock(&kvm->lock);
1426         return ret;
1427 }
1428
1429 static int kvm_s390_set_processor_feat(struct kvm *kvm,
1430                                        struct kvm_device_attr *attr)
1431 {
1432         struct kvm_s390_vm_cpu_feat data;
1433
1434         if (copy_from_user(&data, (void __user *)attr->addr, sizeof(data)))
1435                 return -EFAULT;
1436         if (!bitmap_subset((unsigned long *) data.feat,
1437                            kvm_s390_available_cpu_feat,
1438                            KVM_S390_VM_CPU_FEAT_NR_BITS))
1439                 return -EINVAL;
1440
1441         mutex_lock(&kvm->lock);
1442         if (kvm->created_vcpus) {
1443                 mutex_unlock(&kvm->lock);
1444                 return -EBUSY;
1445         }
1446         bitmap_from_arr64(kvm->arch.cpu_feat, data.feat, KVM_S390_VM_CPU_FEAT_NR_BITS);
1447         mutex_unlock(&kvm->lock);
1448         VM_EVENT(kvm, 3, "SET: guest feat: 0x%16.16llx.0x%16.16llx.0x%16.16llx",
1449                          data.feat[0],
1450                          data.feat[1],
1451                          data.feat[2]);
1452         return 0;
1453 }
1454
1455 static int kvm_s390_set_processor_subfunc(struct kvm *kvm,
1456                                           struct kvm_device_attr *attr)
1457 {
1458         mutex_lock(&kvm->lock);
1459         if (kvm->created_vcpus) {
1460                 mutex_unlock(&kvm->lock);
1461                 return -EBUSY;
1462         }
1463
1464         if (copy_from_user(&kvm->arch.model.subfuncs, (void __user *)attr->addr,
1465                            sizeof(struct kvm_s390_vm_cpu_subfunc))) {
1466                 mutex_unlock(&kvm->lock);
1467                 return -EFAULT;
1468         }
1469         mutex_unlock(&kvm->lock);
1470
1471         VM_EVENT(kvm, 3, "SET: guest PLO    subfunc 0x%16.16lx.%16.16lx.%16.16lx.%16.16lx",
1472                  ((unsigned long *) &kvm->arch.model.subfuncs.plo)[0],
1473                  ((unsigned long *) &kvm->arch.model.subfuncs.plo)[1],
1474                  ((unsigned long *) &kvm->arch.model.subfuncs.plo)[2],
1475                  ((unsigned long *) &kvm->arch.model.subfuncs.plo)[3]);
1476         VM_EVENT(kvm, 3, "SET: guest PTFF   subfunc 0x%16.16lx.%16.16lx",
1477                  ((unsigned long *) &kvm->arch.model.subfuncs.ptff)[0],
1478                  ((unsigned long *) &kvm->arch.model.subfuncs.ptff)[1]);
1479         VM_EVENT(kvm, 3, "SET: guest KMAC   subfunc 0x%16.16lx.%16.16lx",
1480                  ((unsigned long *) &kvm->arch.model.subfuncs.kmac)[0],
1481                  ((unsigned long *) &kvm->arch.model.subfuncs.kmac)[1]);
1482         VM_EVENT(kvm, 3, "SET: guest KMC    subfunc 0x%16.16lx.%16.16lx",
1483                  ((unsigned long *) &kvm->arch.model.subfuncs.kmc)[0],
1484                  ((unsigned long *) &kvm->arch.model.subfuncs.kmc)[1]);
1485         VM_EVENT(kvm, 3, "SET: guest KM     subfunc 0x%16.16lx.%16.16lx",
1486                  ((unsigned long *) &kvm->arch.model.subfuncs.km)[0],
1487                  ((unsigned long *) &kvm->arch.model.subfuncs.km)[1]);
1488         VM_EVENT(kvm, 3, "SET: guest KIMD   subfunc 0x%16.16lx.%16.16lx",
1489                  ((unsigned long *) &kvm->arch.model.subfuncs.kimd)[0],
1490                  ((unsigned long *) &kvm->arch.model.subfuncs.kimd)[1]);
1491         VM_EVENT(kvm, 3, "SET: guest KLMD   subfunc 0x%16.16lx.%16.16lx",
1492                  ((unsigned long *) &kvm->arch.model.subfuncs.klmd)[0],
1493                  ((unsigned long *) &kvm->arch.model.subfuncs.klmd)[1]);
1494         VM_EVENT(kvm, 3, "SET: guest PCKMO  subfunc 0x%16.16lx.%16.16lx",
1495                  ((unsigned long *) &kvm->arch.model.subfuncs.pckmo)[0],
1496                  ((unsigned long *) &kvm->arch.model.subfuncs.pckmo)[1]);
1497         VM_EVENT(kvm, 3, "SET: guest KMCTR  subfunc 0x%16.16lx.%16.16lx",
1498                  ((unsigned long *) &kvm->arch.model.subfuncs.kmctr)[0],
1499                  ((unsigned long *) &kvm->arch.model.subfuncs.kmctr)[1]);
1500         VM_EVENT(kvm, 3, "SET: guest KMF    subfunc 0x%16.16lx.%16.16lx",
1501                  ((unsigned long *) &kvm->arch.model.subfuncs.kmf)[0],
1502                  ((unsigned long *) &kvm->arch.model.subfuncs.kmf)[1]);
1503         VM_EVENT(kvm, 3, "SET: guest KMO    subfunc 0x%16.16lx.%16.16lx",
1504                  ((unsigned long *) &kvm->arch.model.subfuncs.kmo)[0],
1505                  ((unsigned long *) &kvm->arch.model.subfuncs.kmo)[1]);
1506         VM_EVENT(kvm, 3, "SET: guest PCC    subfunc 0x%16.16lx.%16.16lx",
1507                  ((unsigned long *) &kvm->arch.model.subfuncs.pcc)[0],
1508                  ((unsigned long *) &kvm->arch.model.subfuncs.pcc)[1]);
1509         VM_EVENT(kvm, 3, "SET: guest PPNO   subfunc 0x%16.16lx.%16.16lx",
1510                  ((unsigned long *) &kvm->arch.model.subfuncs.ppno)[0],
1511                  ((unsigned long *) &kvm->arch.model.subfuncs.ppno)[1]);
1512         VM_EVENT(kvm, 3, "SET: guest KMA    subfunc 0x%16.16lx.%16.16lx",
1513                  ((unsigned long *) &kvm->arch.model.subfuncs.kma)[0],
1514                  ((unsigned long *) &kvm->arch.model.subfuncs.kma)[1]);
1515         VM_EVENT(kvm, 3, "SET: guest KDSA   subfunc 0x%16.16lx.%16.16lx",
1516                  ((unsigned long *) &kvm->arch.model.subfuncs.kdsa)[0],
1517                  ((unsigned long *) &kvm->arch.model.subfuncs.kdsa)[1]);
1518         VM_EVENT(kvm, 3, "SET: guest SORTL  subfunc 0x%16.16lx.%16.16lx.%16.16lx.%16.16lx",
1519                  ((unsigned long *) &kvm->arch.model.subfuncs.sortl)[0],
1520                  ((unsigned long *) &kvm->arch.model.subfuncs.sortl)[1],
1521                  ((unsigned long *) &kvm->arch.model.subfuncs.sortl)[2],
1522                  ((unsigned long *) &kvm->arch.model.subfuncs.sortl)[3]);
1523         VM_EVENT(kvm, 3, "SET: guest DFLTCC subfunc 0x%16.16lx.%16.16lx.%16.16lx.%16.16lx",
1524                  ((unsigned long *) &kvm->arch.model.subfuncs.dfltcc)[0],
1525                  ((unsigned long *) &kvm->arch.model.subfuncs.dfltcc)[1],
1526                  ((unsigned long *) &kvm->arch.model.subfuncs.dfltcc)[2],
1527                  ((unsigned long *) &kvm->arch.model.subfuncs.dfltcc)[3]);
1528
1529         return 0;
1530 }
1531
1532 static int kvm_s390_set_cpu_model(struct kvm *kvm, struct kvm_device_attr *attr)
1533 {
1534         int ret = -ENXIO;
1535
1536         switch (attr->attr) {
1537         case KVM_S390_VM_CPU_PROCESSOR:
1538                 ret = kvm_s390_set_processor(kvm, attr);
1539                 break;
1540         case KVM_S390_VM_CPU_PROCESSOR_FEAT:
1541                 ret = kvm_s390_set_processor_feat(kvm, attr);
1542                 break;
1543         case KVM_S390_VM_CPU_PROCESSOR_SUBFUNC:
1544                 ret = kvm_s390_set_processor_subfunc(kvm, attr);
1545                 break;
1546         }
1547         return ret;
1548 }
1549
1550 static int kvm_s390_get_processor(struct kvm *kvm, struct kvm_device_attr *attr)
1551 {
1552         struct kvm_s390_vm_cpu_processor *proc;
1553         int ret = 0;
1554
1555         proc = kzalloc(sizeof(*proc), GFP_KERNEL_ACCOUNT);
1556         if (!proc) {
1557                 ret = -ENOMEM;
1558                 goto out;
1559         }
1560         proc->cpuid = kvm->arch.model.cpuid;
1561         proc->ibc = kvm->arch.model.ibc;
1562         memcpy(&proc->fac_list, kvm->arch.model.fac_list,
1563                S390_ARCH_FAC_LIST_SIZE_BYTE);
1564         VM_EVENT(kvm, 3, "GET: guest ibc: 0x%4.4x, guest cpuid: 0x%16.16llx",
1565                  kvm->arch.model.ibc,
1566                  kvm->arch.model.cpuid);
1567         VM_EVENT(kvm, 3, "GET: guest faclist: 0x%16.16llx.%16.16llx.%16.16llx",
1568                  kvm->arch.model.fac_list[0],
1569                  kvm->arch.model.fac_list[1],
1570                  kvm->arch.model.fac_list[2]);
1571         if (copy_to_user((void __user *)attr->addr, proc, sizeof(*proc)))
1572                 ret = -EFAULT;
1573         kfree(proc);
1574 out:
1575         return ret;
1576 }
1577
1578 static int kvm_s390_get_machine(struct kvm *kvm, struct kvm_device_attr *attr)
1579 {
1580         struct kvm_s390_vm_cpu_machine *mach;
1581         int ret = 0;
1582
1583         mach = kzalloc(sizeof(*mach), GFP_KERNEL_ACCOUNT);
1584         if (!mach) {
1585                 ret = -ENOMEM;
1586                 goto out;
1587         }
1588         get_cpu_id((struct cpuid *) &mach->cpuid);
1589         mach->ibc = sclp.ibc;
1590         memcpy(&mach->fac_mask, kvm->arch.model.fac_mask,
1591                S390_ARCH_FAC_LIST_SIZE_BYTE);
1592         memcpy((unsigned long *)&mach->fac_list, stfle_fac_list,
1593                sizeof(stfle_fac_list));
1594         VM_EVENT(kvm, 3, "GET: host ibc:  0x%4.4x, host cpuid:  0x%16.16llx",
1595                  kvm->arch.model.ibc,
1596                  kvm->arch.model.cpuid);
1597         VM_EVENT(kvm, 3, "GET: host facmask:  0x%16.16llx.%16.16llx.%16.16llx",
1598                  mach->fac_mask[0],
1599                  mach->fac_mask[1],
1600                  mach->fac_mask[2]);
1601         VM_EVENT(kvm, 3, "GET: host faclist:  0x%16.16llx.%16.16llx.%16.16llx",
1602                  mach->fac_list[0],
1603                  mach->fac_list[1],
1604                  mach->fac_list[2]);
1605         if (copy_to_user((void __user *)attr->addr, mach, sizeof(*mach)))
1606                 ret = -EFAULT;
1607         kfree(mach);
1608 out:
1609         return ret;
1610 }
1611
1612 static int kvm_s390_get_processor_feat(struct kvm *kvm,
1613                                        struct kvm_device_attr *attr)
1614 {
1615         struct kvm_s390_vm_cpu_feat data;
1616
1617         bitmap_to_arr64(data.feat, kvm->arch.cpu_feat, KVM_S390_VM_CPU_FEAT_NR_BITS);
1618         if (copy_to_user((void __user *)attr->addr, &data, sizeof(data)))
1619                 return -EFAULT;
1620         VM_EVENT(kvm, 3, "GET: guest feat: 0x%16.16llx.0x%16.16llx.0x%16.16llx",
1621                          data.feat[0],
1622                          data.feat[1],
1623                          data.feat[2]);
1624         return 0;
1625 }
1626
1627 static int kvm_s390_get_machine_feat(struct kvm *kvm,
1628                                      struct kvm_device_attr *attr)
1629 {
1630         struct kvm_s390_vm_cpu_feat data;
1631
1632         bitmap_to_arr64(data.feat, kvm_s390_available_cpu_feat, KVM_S390_VM_CPU_FEAT_NR_BITS);
1633         if (copy_to_user((void __user *)attr->addr, &data, sizeof(data)))
1634                 return -EFAULT;
1635         VM_EVENT(kvm, 3, "GET: host feat:  0x%16.16llx.0x%16.16llx.0x%16.16llx",
1636                          data.feat[0],
1637                          data.feat[1],
1638                          data.feat[2]);
1639         return 0;
1640 }
1641
1642 static int kvm_s390_get_processor_subfunc(struct kvm *kvm,
1643                                           struct kvm_device_attr *attr)
1644 {
1645         if (copy_to_user((void __user *)attr->addr, &kvm->arch.model.subfuncs,
1646             sizeof(struct kvm_s390_vm_cpu_subfunc)))
1647                 return -EFAULT;
1648
1649         VM_EVENT(kvm, 3, "GET: guest PLO    subfunc 0x%16.16lx.%16.16lx.%16.16lx.%16.16lx",
1650                  ((unsigned long *) &kvm->arch.model.subfuncs.plo)[0],
1651                  ((unsigned long *) &kvm->arch.model.subfuncs.plo)[1],
1652                  ((unsigned long *) &kvm->arch.model.subfuncs.plo)[2],
1653                  ((unsigned long *) &kvm->arch.model.subfuncs.plo)[3]);
1654         VM_EVENT(kvm, 3, "GET: guest PTFF   subfunc 0x%16.16lx.%16.16lx",
1655                  ((unsigned long *) &kvm->arch.model.subfuncs.ptff)[0],
1656                  ((unsigned long *) &kvm->arch.model.subfuncs.ptff)[1]);
1657         VM_EVENT(kvm, 3, "GET: guest KMAC   subfunc 0x%16.16lx.%16.16lx",
1658                  ((unsigned long *) &kvm->arch.model.subfuncs.kmac)[0],
1659                  ((unsigned long *) &kvm->arch.model.subfuncs.kmac)[1]);
1660         VM_EVENT(kvm, 3, "GET: guest KMC    subfunc 0x%16.16lx.%16.16lx",
1661                  ((unsigned long *) &kvm->arch.model.subfuncs.kmc)[0],
1662                  ((unsigned long *) &kvm->arch.model.subfuncs.kmc)[1]);
1663         VM_EVENT(kvm, 3, "GET: guest KM     subfunc 0x%16.16lx.%16.16lx",
1664                  ((unsigned long *) &kvm->arch.model.subfuncs.km)[0],
1665                  ((unsigned long *) &kvm->arch.model.subfuncs.km)[1]);
1666         VM_EVENT(kvm, 3, "GET: guest KIMD   subfunc 0x%16.16lx.%16.16lx",
1667                  ((unsigned long *) &kvm->arch.model.subfuncs.kimd)[0],
1668                  ((unsigned long *) &kvm->arch.model.subfuncs.kimd)[1]);
1669         VM_EVENT(kvm, 3, "GET: guest KLMD   subfunc 0x%16.16lx.%16.16lx",
1670                  ((unsigned long *) &kvm->arch.model.subfuncs.klmd)[0],
1671                  ((unsigned long *) &kvm->arch.model.subfuncs.klmd)[1]);
1672         VM_EVENT(kvm, 3, "GET: guest PCKMO  subfunc 0x%16.16lx.%16.16lx",
1673                  ((unsigned long *) &kvm->arch.model.subfuncs.pckmo)[0],
1674                  ((unsigned long *) &kvm->arch.model.subfuncs.pckmo)[1]);
1675         VM_EVENT(kvm, 3, "GET: guest KMCTR  subfunc 0x%16.16lx.%16.16lx",
1676                  ((unsigned long *) &kvm->arch.model.subfuncs.kmctr)[0],
1677                  ((unsigned long *) &kvm->arch.model.subfuncs.kmctr)[1]);
1678         VM_EVENT(kvm, 3, "GET: guest KMF    subfunc 0x%16.16lx.%16.16lx",
1679                  ((unsigned long *) &kvm->arch.model.subfuncs.kmf)[0],
1680                  ((unsigned long *) &kvm->arch.model.subfuncs.kmf)[1]);
1681         VM_EVENT(kvm, 3, "GET: guest KMO    subfunc 0x%16.16lx.%16.16lx",
1682                  ((unsigned long *) &kvm->arch.model.subfuncs.kmo)[0],
1683                  ((unsigned long *) &kvm->arch.model.subfuncs.kmo)[1]);
1684         VM_EVENT(kvm, 3, "GET: guest PCC    subfunc 0x%16.16lx.%16.16lx",
1685                  ((unsigned long *) &kvm->arch.model.subfuncs.pcc)[0],
1686                  ((unsigned long *) &kvm->arch.model.subfuncs.pcc)[1]);
1687         VM_EVENT(kvm, 3, "GET: guest PPNO   subfunc 0x%16.16lx.%16.16lx",
1688                  ((unsigned long *) &kvm->arch.model.subfuncs.ppno)[0],
1689                  ((unsigned long *) &kvm->arch.model.subfuncs.ppno)[1]);
1690         VM_EVENT(kvm, 3, "GET: guest KMA    subfunc 0x%16.16lx.%16.16lx",
1691                  ((unsigned long *) &kvm->arch.model.subfuncs.kma)[0],
1692                  ((unsigned long *) &kvm->arch.model.subfuncs.kma)[1]);
1693         VM_EVENT(kvm, 3, "GET: guest KDSA   subfunc 0x%16.16lx.%16.16lx",
1694                  ((unsigned long *) &kvm->arch.model.subfuncs.kdsa)[0],
1695                  ((unsigned long *) &kvm->arch.model.subfuncs.kdsa)[1]);
1696         VM_EVENT(kvm, 3, "GET: guest SORTL  subfunc 0x%16.16lx.%16.16lx.%16.16lx.%16.16lx",
1697                  ((unsigned long *) &kvm->arch.model.subfuncs.sortl)[0],
1698                  ((unsigned long *) &kvm->arch.model.subfuncs.sortl)[1],
1699                  ((unsigned long *) &kvm->arch.model.subfuncs.sortl)[2],
1700                  ((unsigned long *) &kvm->arch.model.subfuncs.sortl)[3]);
1701         VM_EVENT(kvm, 3, "GET: guest DFLTCC subfunc 0x%16.16lx.%16.16lx.%16.16lx.%16.16lx",
1702                  ((unsigned long *) &kvm->arch.model.subfuncs.dfltcc)[0],
1703                  ((unsigned long *) &kvm->arch.model.subfuncs.dfltcc)[1],
1704                  ((unsigned long *) &kvm->arch.model.subfuncs.dfltcc)[2],
1705                  ((unsigned long *) &kvm->arch.model.subfuncs.dfltcc)[3]);
1706
1707         return 0;
1708 }
1709
1710 static int kvm_s390_get_machine_subfunc(struct kvm *kvm,
1711                                         struct kvm_device_attr *attr)
1712 {
1713         if (copy_to_user((void __user *)attr->addr, &kvm_s390_available_subfunc,
1714             sizeof(struct kvm_s390_vm_cpu_subfunc)))
1715                 return -EFAULT;
1716
1717         VM_EVENT(kvm, 3, "GET: host  PLO    subfunc 0x%16.16lx.%16.16lx.%16.16lx.%16.16lx",
1718                  ((unsigned long *) &kvm_s390_available_subfunc.plo)[0],
1719                  ((unsigned long *) &kvm_s390_available_subfunc.plo)[1],
1720                  ((unsigned long *) &kvm_s390_available_subfunc.plo)[2],
1721                  ((unsigned long *) &kvm_s390_available_subfunc.plo)[3]);
1722         VM_EVENT(kvm, 3, "GET: host  PTFF   subfunc 0x%16.16lx.%16.16lx",
1723                  ((unsigned long *) &kvm_s390_available_subfunc.ptff)[0],
1724                  ((unsigned long *) &kvm_s390_available_subfunc.ptff)[1]);
1725         VM_EVENT(kvm, 3, "GET: host  KMAC   subfunc 0x%16.16lx.%16.16lx",
1726                  ((unsigned long *) &kvm_s390_available_subfunc.kmac)[0],
1727                  ((unsigned long *) &kvm_s390_available_subfunc.kmac)[1]);
1728         VM_EVENT(kvm, 3, "GET: host  KMC    subfunc 0x%16.16lx.%16.16lx",
1729                  ((unsigned long *) &kvm_s390_available_subfunc.kmc)[0],
1730                  ((unsigned long *) &kvm_s390_available_subfunc.kmc)[1]);
1731         VM_EVENT(kvm, 3, "GET: host  KM     subfunc 0x%16.16lx.%16.16lx",
1732                  ((unsigned long *) &kvm_s390_available_subfunc.km)[0],
1733                  ((unsigned long *) &kvm_s390_available_subfunc.km)[1]);
1734         VM_EVENT(kvm, 3, "GET: host  KIMD   subfunc 0x%16.16lx.%16.16lx",
1735                  ((unsigned long *) &kvm_s390_available_subfunc.kimd)[0],
1736                  ((unsigned long *) &kvm_s390_available_subfunc.kimd)[1]);
1737         VM_EVENT(kvm, 3, "GET: host  KLMD   subfunc 0x%16.16lx.%16.16lx",
1738                  ((unsigned long *) &kvm_s390_available_subfunc.klmd)[0],
1739                  ((unsigned long *) &kvm_s390_available_subfunc.klmd)[1]);
1740         VM_EVENT(kvm, 3, "GET: host  PCKMO  subfunc 0x%16.16lx.%16.16lx",
1741                  ((unsigned long *) &kvm_s390_available_subfunc.pckmo)[0],
1742                  ((unsigned long *) &kvm_s390_available_subfunc.pckmo)[1]);
1743         VM_EVENT(kvm, 3, "GET: host  KMCTR  subfunc 0x%16.16lx.%16.16lx",
1744                  ((unsigned long *) &kvm_s390_available_subfunc.kmctr)[0],
1745                  ((unsigned long *) &kvm_s390_available_subfunc.kmctr)[1]);
1746         VM_EVENT(kvm, 3, "GET: host  KMF    subfunc 0x%16.16lx.%16.16lx",
1747                  ((unsigned long *) &kvm_s390_available_subfunc.kmf)[0],
1748                  ((unsigned long *) &kvm_s390_available_subfunc.kmf)[1]);
1749         VM_EVENT(kvm, 3, "GET: host  KMO    subfunc 0x%16.16lx.%16.16lx",
1750                  ((unsigned long *) &kvm_s390_available_subfunc.kmo)[0],
1751                  ((unsigned long *) &kvm_s390_available_subfunc.kmo)[1]);
1752         VM_EVENT(kvm, 3, "GET: host  PCC    subfunc 0x%16.16lx.%16.16lx",
1753                  ((unsigned long *) &kvm_s390_available_subfunc.pcc)[0],
1754                  ((unsigned long *) &kvm_s390_available_subfunc.pcc)[1]);
1755         VM_EVENT(kvm, 3, "GET: host  PPNO   subfunc 0x%16.16lx.%16.16lx",
1756                  ((unsigned long *) &kvm_s390_available_subfunc.ppno)[0],
1757                  ((unsigned long *) &kvm_s390_available_subfunc.ppno)[1]);
1758         VM_EVENT(kvm, 3, "GET: host  KMA    subfunc 0x%16.16lx.%16.16lx",
1759                  ((unsigned long *) &kvm_s390_available_subfunc.kma)[0],
1760                  ((unsigned long *) &kvm_s390_available_subfunc.kma)[1]);
1761         VM_EVENT(kvm, 3, "GET: host  KDSA   subfunc 0x%16.16lx.%16.16lx",
1762                  ((unsigned long *) &kvm_s390_available_subfunc.kdsa)[0],
1763                  ((unsigned long *) &kvm_s390_available_subfunc.kdsa)[1]);
1764         VM_EVENT(kvm, 3, "GET: host  SORTL  subfunc 0x%16.16lx.%16.16lx.%16.16lx.%16.16lx",
1765                  ((unsigned long *) &kvm_s390_available_subfunc.sortl)[0],
1766                  ((unsigned long *) &kvm_s390_available_subfunc.sortl)[1],
1767                  ((unsigned long *) &kvm_s390_available_subfunc.sortl)[2],
1768                  ((unsigned long *) &kvm_s390_available_subfunc.sortl)[3]);
1769         VM_EVENT(kvm, 3, "GET: host  DFLTCC subfunc 0x%16.16lx.%16.16lx.%16.16lx.%16.16lx",
1770                  ((unsigned long *) &kvm_s390_available_subfunc.dfltcc)[0],
1771                  ((unsigned long *) &kvm_s390_available_subfunc.dfltcc)[1],
1772                  ((unsigned long *) &kvm_s390_available_subfunc.dfltcc)[2],
1773                  ((unsigned long *) &kvm_s390_available_subfunc.dfltcc)[3]);
1774
1775         return 0;
1776 }
1777
1778 static int kvm_s390_get_cpu_model(struct kvm *kvm, struct kvm_device_attr *attr)
1779 {
1780         int ret = -ENXIO;
1781
1782         switch (attr->attr) {
1783         case KVM_S390_VM_CPU_PROCESSOR:
1784                 ret = kvm_s390_get_processor(kvm, attr);
1785                 break;
1786         case KVM_S390_VM_CPU_MACHINE:
1787                 ret = kvm_s390_get_machine(kvm, attr);
1788                 break;
1789         case KVM_S390_VM_CPU_PROCESSOR_FEAT:
1790                 ret = kvm_s390_get_processor_feat(kvm, attr);
1791                 break;
1792         case KVM_S390_VM_CPU_MACHINE_FEAT:
1793                 ret = kvm_s390_get_machine_feat(kvm, attr);
1794                 break;
1795         case KVM_S390_VM_CPU_PROCESSOR_SUBFUNC:
1796                 ret = kvm_s390_get_processor_subfunc(kvm, attr);
1797                 break;
1798         case KVM_S390_VM_CPU_MACHINE_SUBFUNC:
1799                 ret = kvm_s390_get_machine_subfunc(kvm, attr);
1800                 break;
1801         }
1802         return ret;
1803 }
1804
1805 /**
1806  * kvm_s390_update_topology_change_report - update CPU topology change report
1807  * @kvm: guest KVM description
1808  * @val: set or clear the MTCR bit
1809  *
1810  * Updates the Multiprocessor Topology-Change-Report bit to signal
1811  * the guest with a topology change.
1812  * This is only relevant if the topology facility is present.
1813  *
1814  * The SCA version, bsca or esca, doesn't matter as offset is the same.
1815  */
1816 static void kvm_s390_update_topology_change_report(struct kvm *kvm, bool val)
1817 {
1818         union sca_utility new, old;
1819         struct bsca_block *sca;
1820
1821         read_lock(&kvm->arch.sca_lock);
1822         sca = kvm->arch.sca;
1823         do {
1824                 old = READ_ONCE(sca->utility);
1825                 new = old;
1826                 new.mtcr = val;
1827         } while (cmpxchg(&sca->utility.val, old.val, new.val) != old.val);
1828         read_unlock(&kvm->arch.sca_lock);
1829 }
1830
1831 static int kvm_s390_set_topo_change_indication(struct kvm *kvm,
1832                                                struct kvm_device_attr *attr)
1833 {
1834         if (!test_kvm_facility(kvm, 11))
1835                 return -ENXIO;
1836
1837         kvm_s390_update_topology_change_report(kvm, !!attr->attr);
1838         return 0;
1839 }
1840
1841 static int kvm_s390_get_topo_change_indication(struct kvm *kvm,
1842                                                struct kvm_device_attr *attr)
1843 {
1844         u8 topo;
1845
1846         if (!test_kvm_facility(kvm, 11))
1847                 return -ENXIO;
1848
1849         read_lock(&kvm->arch.sca_lock);
1850         topo = ((struct bsca_block *)kvm->arch.sca)->utility.mtcr;
1851         read_unlock(&kvm->arch.sca_lock);
1852
1853         return put_user(topo, (u8 __user *)attr->addr);
1854 }
1855
1856 static int kvm_s390_vm_set_attr(struct kvm *kvm, struct kvm_device_attr *attr)
1857 {
1858         int ret;
1859
1860         switch (attr->group) {
1861         case KVM_S390_VM_MEM_CTRL:
1862                 ret = kvm_s390_set_mem_control(kvm, attr);
1863                 break;
1864         case KVM_S390_VM_TOD:
1865                 ret = kvm_s390_set_tod(kvm, attr);
1866                 break;
1867         case KVM_S390_VM_CPU_MODEL:
1868                 ret = kvm_s390_set_cpu_model(kvm, attr);
1869                 break;
1870         case KVM_S390_VM_CRYPTO:
1871                 ret = kvm_s390_vm_set_crypto(kvm, attr);
1872                 break;
1873         case KVM_S390_VM_MIGRATION:
1874                 ret = kvm_s390_vm_set_migration(kvm, attr);
1875                 break;
1876         case KVM_S390_VM_CPU_TOPOLOGY:
1877                 ret = kvm_s390_set_topo_change_indication(kvm, attr);
1878                 break;
1879         default:
1880                 ret = -ENXIO;
1881                 break;
1882         }
1883
1884         return ret;
1885 }
1886
1887 static int kvm_s390_vm_get_attr(struct kvm *kvm, struct kvm_device_attr *attr)
1888 {
1889         int ret;
1890
1891         switch (attr->group) {
1892         case KVM_S390_VM_MEM_CTRL:
1893                 ret = kvm_s390_get_mem_control(kvm, attr);
1894                 break;
1895         case KVM_S390_VM_TOD:
1896                 ret = kvm_s390_get_tod(kvm, attr);
1897                 break;
1898         case KVM_S390_VM_CPU_MODEL:
1899                 ret = kvm_s390_get_cpu_model(kvm, attr);
1900                 break;
1901         case KVM_S390_VM_MIGRATION:
1902                 ret = kvm_s390_vm_get_migration(kvm, attr);
1903                 break;
1904         case KVM_S390_VM_CPU_TOPOLOGY:
1905                 ret = kvm_s390_get_topo_change_indication(kvm, attr);
1906                 break;
1907         default:
1908                 ret = -ENXIO;
1909                 break;
1910         }
1911
1912         return ret;
1913 }
1914
1915 static int kvm_s390_vm_has_attr(struct kvm *kvm, struct kvm_device_attr *attr)
1916 {
1917         int ret;
1918
1919         switch (attr->group) {
1920         case KVM_S390_VM_MEM_CTRL:
1921                 switch (attr->attr) {
1922                 case KVM_S390_VM_MEM_ENABLE_CMMA:
1923                 case KVM_S390_VM_MEM_CLR_CMMA:
1924                         ret = sclp.has_cmma ? 0 : -ENXIO;
1925                         break;
1926                 case KVM_S390_VM_MEM_LIMIT_SIZE:
1927                         ret = 0;
1928                         break;
1929                 default:
1930                         ret = -ENXIO;
1931                         break;
1932                 }
1933                 break;
1934         case KVM_S390_VM_TOD:
1935                 switch (attr->attr) {
1936                 case KVM_S390_VM_TOD_LOW:
1937                 case KVM_S390_VM_TOD_HIGH:
1938                         ret = 0;
1939                         break;
1940                 default:
1941                         ret = -ENXIO;
1942                         break;
1943                 }
1944                 break;
1945         case KVM_S390_VM_CPU_MODEL:
1946                 switch (attr->attr) {
1947                 case KVM_S390_VM_CPU_PROCESSOR:
1948                 case KVM_S390_VM_CPU_MACHINE:
1949                 case KVM_S390_VM_CPU_PROCESSOR_FEAT:
1950                 case KVM_S390_VM_CPU_MACHINE_FEAT:
1951                 case KVM_S390_VM_CPU_MACHINE_SUBFUNC:
1952                 case KVM_S390_VM_CPU_PROCESSOR_SUBFUNC:
1953                         ret = 0;
1954                         break;
1955                 default:
1956                         ret = -ENXIO;
1957                         break;
1958                 }
1959                 break;
1960         case KVM_S390_VM_CRYPTO:
1961                 switch (attr->attr) {
1962                 case KVM_S390_VM_CRYPTO_ENABLE_AES_KW:
1963                 case KVM_S390_VM_CRYPTO_ENABLE_DEA_KW:
1964                 case KVM_S390_VM_CRYPTO_DISABLE_AES_KW:
1965                 case KVM_S390_VM_CRYPTO_DISABLE_DEA_KW:
1966                         ret = 0;
1967                         break;
1968                 case KVM_S390_VM_CRYPTO_ENABLE_APIE:
1969                 case KVM_S390_VM_CRYPTO_DISABLE_APIE:
1970                         ret = ap_instructions_available() ? 0 : -ENXIO;
1971                         break;
1972                 default:
1973                         ret = -ENXIO;
1974                         break;
1975                 }
1976                 break;
1977         case KVM_S390_VM_MIGRATION:
1978                 ret = 0;
1979                 break;
1980         case KVM_S390_VM_CPU_TOPOLOGY:
1981                 ret = test_kvm_facility(kvm, 11) ? 0 : -ENXIO;
1982                 break;
1983         default:
1984                 ret = -ENXIO;
1985                 break;
1986         }
1987
1988         return ret;
1989 }
1990
1991 static long kvm_s390_get_skeys(struct kvm *kvm, struct kvm_s390_skeys *args)
1992 {
1993         uint8_t *keys;
1994         uint64_t hva;
1995         int srcu_idx, i, r = 0;
1996
1997         if (args->flags != 0)
1998                 return -EINVAL;
1999
2000         /* Is this guest using storage keys? */
2001         if (!mm_uses_skeys(current->mm))
2002                 return KVM_S390_GET_SKEYS_NONE;
2003
2004         /* Enforce sane limit on memory allocation */
2005         if (args->count < 1 || args->count > KVM_S390_SKEYS_MAX)
2006                 return -EINVAL;
2007
2008         keys = kvmalloc_array(args->count, sizeof(uint8_t), GFP_KERNEL_ACCOUNT);
2009         if (!keys)
2010                 return -ENOMEM;
2011
2012         mmap_read_lock(current->mm);
2013         srcu_idx = srcu_read_lock(&kvm->srcu);
2014         for (i = 0; i < args->count; i++) {
2015                 hva = gfn_to_hva(kvm, args->start_gfn + i);
2016                 if (kvm_is_error_hva(hva)) {
2017                         r = -EFAULT;
2018                         break;
2019                 }
2020
2021                 r = get_guest_storage_key(current->mm, hva, &keys[i]);
2022                 if (r)
2023                         break;
2024         }
2025         srcu_read_unlock(&kvm->srcu, srcu_idx);
2026         mmap_read_unlock(current->mm);
2027
2028         if (!r) {
2029                 r = copy_to_user((uint8_t __user *)args->skeydata_addr, keys,
2030                                  sizeof(uint8_t) * args->count);
2031                 if (r)
2032                         r = -EFAULT;
2033         }
2034
2035         kvfree(keys);
2036         return r;
2037 }
2038
2039 static long kvm_s390_set_skeys(struct kvm *kvm, struct kvm_s390_skeys *args)
2040 {
2041         uint8_t *keys;
2042         uint64_t hva;
2043         int srcu_idx, i, r = 0;
2044         bool unlocked;
2045
2046         if (args->flags != 0)
2047                 return -EINVAL;
2048
2049         /* Enforce sane limit on memory allocation */
2050         if (args->count < 1 || args->count > KVM_S390_SKEYS_MAX)
2051                 return -EINVAL;
2052
2053         keys = kvmalloc_array(args->count, sizeof(uint8_t), GFP_KERNEL_ACCOUNT);
2054         if (!keys)
2055                 return -ENOMEM;
2056
2057         r = copy_from_user(keys, (uint8_t __user *)args->skeydata_addr,
2058                            sizeof(uint8_t) * args->count);
2059         if (r) {
2060                 r = -EFAULT;
2061                 goto out;
2062         }
2063
2064         /* Enable storage key handling for the guest */
2065         r = s390_enable_skey();
2066         if (r)
2067                 goto out;
2068
2069         i = 0;
2070         mmap_read_lock(current->mm);
2071         srcu_idx = srcu_read_lock(&kvm->srcu);
2072         while (i < args->count) {
2073                 unlocked = false;
2074                 hva = gfn_to_hva(kvm, args->start_gfn + i);
2075                 if (kvm_is_error_hva(hva)) {
2076                         r = -EFAULT;
2077                         break;
2078                 }
2079
2080                 /* Lowest order bit is reserved */
2081                 if (keys[i] & 0x01) {
2082                         r = -EINVAL;
2083                         break;
2084                 }
2085
2086                 r = set_guest_storage_key(current->mm, hva, keys[i], 0);
2087                 if (r) {
2088                         r = fixup_user_fault(current->mm, hva,
2089                                              FAULT_FLAG_WRITE, &unlocked);
2090                         if (r)
2091                                 break;
2092                 }
2093                 if (!r)
2094                         i++;
2095         }
2096         srcu_read_unlock(&kvm->srcu, srcu_idx);
2097         mmap_read_unlock(current->mm);
2098 out:
2099         kvfree(keys);
2100         return r;
2101 }
2102
2103 /*
2104  * Base address and length must be sent at the start of each block, therefore
2105  * it's cheaper to send some clean data, as long as it's less than the size of
2106  * two longs.
2107  */
2108 #define KVM_S390_MAX_BIT_DISTANCE (2 * sizeof(void *))
2109 /* for consistency */
2110 #define KVM_S390_CMMA_SIZE_MAX ((u32)KVM_S390_SKEYS_MAX)
2111
2112 static int kvm_s390_peek_cmma(struct kvm *kvm, struct kvm_s390_cmma_log *args,
2113                               u8 *res, unsigned long bufsize)
2114 {
2115         unsigned long pgstev, hva, cur_gfn = args->start_gfn;
2116
2117         args->count = 0;
2118         while (args->count < bufsize) {
2119                 hva = gfn_to_hva(kvm, cur_gfn);
2120                 /*
2121                  * We return an error if the first value was invalid, but we
2122                  * return successfully if at least one value was copied.
2123                  */
2124                 if (kvm_is_error_hva(hva))
2125                         return args->count ? 0 : -EFAULT;
2126                 if (get_pgste(kvm->mm, hva, &pgstev) < 0)
2127                         pgstev = 0;
2128                 res[args->count++] = (pgstev >> 24) & 0x43;
2129                 cur_gfn++;
2130         }
2131
2132         return 0;
2133 }
2134
2135 static struct kvm_memory_slot *gfn_to_memslot_approx(struct kvm_memslots *slots,
2136                                                      gfn_t gfn)
2137 {
2138         return ____gfn_to_memslot(slots, gfn, true);
2139 }
2140
2141 static unsigned long kvm_s390_next_dirty_cmma(struct kvm_memslots *slots,
2142                                               unsigned long cur_gfn)
2143 {
2144         struct kvm_memory_slot *ms = gfn_to_memslot_approx(slots, cur_gfn);
2145         unsigned long ofs = cur_gfn - ms->base_gfn;
2146         struct rb_node *mnode = &ms->gfn_node[slots->node_idx];
2147
2148         if (ms->base_gfn + ms->npages <= cur_gfn) {
2149                 mnode = rb_next(mnode);
2150                 /* If we are above the highest slot, wrap around */
2151                 if (!mnode)
2152                         mnode = rb_first(&slots->gfn_tree);
2153
2154                 ms = container_of(mnode, struct kvm_memory_slot, gfn_node[slots->node_idx]);
2155                 ofs = 0;
2156         }
2157
2158         if (cur_gfn < ms->base_gfn)
2159                 ofs = 0;
2160
2161         ofs = find_next_bit(kvm_second_dirty_bitmap(ms), ms->npages, ofs);
2162         while (ofs >= ms->npages && (mnode = rb_next(mnode))) {
2163                 ms = container_of(mnode, struct kvm_memory_slot, gfn_node[slots->node_idx]);
2164                 ofs = find_first_bit(kvm_second_dirty_bitmap(ms), ms->npages);
2165         }
2166         return ms->base_gfn + ofs;
2167 }
2168
2169 static int kvm_s390_get_cmma(struct kvm *kvm, struct kvm_s390_cmma_log *args,
2170                              u8 *res, unsigned long bufsize)
2171 {
2172         unsigned long mem_end, cur_gfn, next_gfn, hva, pgstev;
2173         struct kvm_memslots *slots = kvm_memslots(kvm);
2174         struct kvm_memory_slot *ms;
2175
2176         if (unlikely(kvm_memslots_empty(slots)))
2177                 return 0;
2178
2179         cur_gfn = kvm_s390_next_dirty_cmma(slots, args->start_gfn);
2180         ms = gfn_to_memslot(kvm, cur_gfn);
2181         args->count = 0;
2182         args->start_gfn = cur_gfn;
2183         if (!ms)
2184                 return 0;
2185         next_gfn = kvm_s390_next_dirty_cmma(slots, cur_gfn + 1);
2186         mem_end = kvm_s390_get_gfn_end(slots);
2187
2188         while (args->count < bufsize) {
2189                 hva = gfn_to_hva(kvm, cur_gfn);
2190                 if (kvm_is_error_hva(hva))
2191                         return 0;
2192                 /* Decrement only if we actually flipped the bit to 0 */
2193                 if (test_and_clear_bit(cur_gfn - ms->base_gfn, kvm_second_dirty_bitmap(ms)))
2194                         atomic64_dec(&kvm->arch.cmma_dirty_pages);
2195                 if (get_pgste(kvm->mm, hva, &pgstev) < 0)
2196                         pgstev = 0;
2197                 /* Save the value */
2198                 res[args->count++] = (pgstev >> 24) & 0x43;
2199                 /* If the next bit is too far away, stop. */
2200                 if (next_gfn > cur_gfn + KVM_S390_MAX_BIT_DISTANCE)
2201                         return 0;
2202                 /* If we reached the previous "next", find the next one */
2203                 if (cur_gfn == next_gfn)
2204                         next_gfn = kvm_s390_next_dirty_cmma(slots, cur_gfn + 1);
2205                 /* Reached the end of memory or of the buffer, stop */
2206                 if ((next_gfn >= mem_end) ||
2207                     (next_gfn - args->start_gfn >= bufsize))
2208                         return 0;
2209                 cur_gfn++;
2210                 /* Reached the end of the current memslot, take the next one. */
2211                 if (cur_gfn - ms->base_gfn >= ms->npages) {
2212                         ms = gfn_to_memslot(kvm, cur_gfn);
2213                         if (!ms)
2214                                 return 0;
2215                 }
2216         }
2217         return 0;
2218 }
2219
2220 /*
2221  * This function searches for the next page with dirty CMMA attributes, and
2222  * saves the attributes in the buffer up to either the end of the buffer or
2223  * until a block of at least KVM_S390_MAX_BIT_DISTANCE clean bits is found;
2224  * no trailing clean bytes are saved.
2225  * In case no dirty bits were found, or if CMMA was not enabled or used, the
2226  * output buffer will indicate 0 as length.
2227  */
2228 static int kvm_s390_get_cmma_bits(struct kvm *kvm,
2229                                   struct kvm_s390_cmma_log *args)
2230 {
2231         unsigned long bufsize;
2232         int srcu_idx, peek, ret;
2233         u8 *values;
2234
2235         if (!kvm->arch.use_cmma)
2236                 return -ENXIO;
2237         /* Invalid/unsupported flags were specified */
2238         if (args->flags & ~KVM_S390_CMMA_PEEK)
2239                 return -EINVAL;
2240         /* Migration mode query, and we are not doing a migration */
2241         peek = !!(args->flags & KVM_S390_CMMA_PEEK);
2242         if (!peek && !kvm->arch.migration_mode)
2243                 return -EINVAL;
2244         /* CMMA is disabled or was not used, or the buffer has length zero */
2245         bufsize = min(args->count, KVM_S390_CMMA_SIZE_MAX);
2246         if (!bufsize || !kvm->mm->context.uses_cmm) {
2247                 memset(args, 0, sizeof(*args));
2248                 return 0;
2249         }
2250         /* We are not peeking, and there are no dirty pages */
2251         if (!peek && !atomic64_read(&kvm->arch.cmma_dirty_pages)) {
2252                 memset(args, 0, sizeof(*args));
2253                 return 0;
2254         }
2255
2256         values = vmalloc(bufsize);
2257         if (!values)
2258                 return -ENOMEM;
2259
2260         mmap_read_lock(kvm->mm);
2261         srcu_idx = srcu_read_lock(&kvm->srcu);
2262         if (peek)
2263                 ret = kvm_s390_peek_cmma(kvm, args, values, bufsize);
2264         else
2265                 ret = kvm_s390_get_cmma(kvm, args, values, bufsize);
2266         srcu_read_unlock(&kvm->srcu, srcu_idx);
2267         mmap_read_unlock(kvm->mm);
2268
2269         if (kvm->arch.migration_mode)
2270                 args->remaining = atomic64_read(&kvm->arch.cmma_dirty_pages);
2271         else
2272                 args->remaining = 0;
2273
2274         if (copy_to_user((void __user *)args->values, values, args->count))
2275                 ret = -EFAULT;
2276
2277         vfree(values);
2278         return ret;
2279 }
2280
2281 /*
2282  * This function sets the CMMA attributes for the given pages. If the input
2283  * buffer has zero length, no action is taken, otherwise the attributes are
2284  * set and the mm->context.uses_cmm flag is set.
2285  */
2286 static int kvm_s390_set_cmma_bits(struct kvm *kvm,
2287                                   const struct kvm_s390_cmma_log *args)
2288 {
2289         unsigned long hva, mask, pgstev, i;
2290         uint8_t *bits;
2291         int srcu_idx, r = 0;
2292
2293         mask = args->mask;
2294
2295         if (!kvm->arch.use_cmma)
2296                 return -ENXIO;
2297         /* invalid/unsupported flags */
2298         if (args->flags != 0)
2299                 return -EINVAL;
2300         /* Enforce sane limit on memory allocation */
2301         if (args->count > KVM_S390_CMMA_SIZE_MAX)
2302                 return -EINVAL;
2303         /* Nothing to do */
2304         if (args->count == 0)
2305                 return 0;
2306
2307         bits = vmalloc(array_size(sizeof(*bits), args->count));
2308         if (!bits)
2309                 return -ENOMEM;
2310
2311         r = copy_from_user(bits, (void __user *)args->values, args->count);
2312         if (r) {
2313                 r = -EFAULT;
2314                 goto out;
2315         }
2316
2317         mmap_read_lock(kvm->mm);
2318         srcu_idx = srcu_read_lock(&kvm->srcu);
2319         for (i = 0; i < args->count; i++) {
2320                 hva = gfn_to_hva(kvm, args->start_gfn + i);
2321                 if (kvm_is_error_hva(hva)) {
2322                         r = -EFAULT;
2323                         break;
2324                 }
2325
2326                 pgstev = bits[i];
2327                 pgstev = pgstev << 24;
2328                 mask &= _PGSTE_GPS_USAGE_MASK | _PGSTE_GPS_NODAT;
2329                 set_pgste_bits(kvm->mm, hva, mask, pgstev);
2330         }
2331         srcu_read_unlock(&kvm->srcu, srcu_idx);
2332         mmap_read_unlock(kvm->mm);
2333
2334         if (!kvm->mm->context.uses_cmm) {
2335                 mmap_write_lock(kvm->mm);
2336                 kvm->mm->context.uses_cmm = 1;
2337                 mmap_write_unlock(kvm->mm);
2338         }
2339 out:
2340         vfree(bits);
2341         return r;
2342 }
2343
2344 /**
2345  * kvm_s390_cpus_from_pv - Convert all protected vCPUs in a protected VM to
2346  * non protected.
2347  * @kvm: the VM whose protected vCPUs are to be converted
2348  * @rc: return value for the RC field of the UVC (in case of error)
2349  * @rrc: return value for the RRC field of the UVC (in case of error)
2350  *
2351  * Does not stop in case of error, tries to convert as many
2352  * CPUs as possible. In case of error, the RC and RRC of the last error are
2353  * returned.
2354  *
2355  * Return: 0 in case of success, otherwise -EIO
2356  */
2357 int kvm_s390_cpus_from_pv(struct kvm *kvm, u16 *rc, u16 *rrc)
2358 {
2359         struct kvm_vcpu *vcpu;
2360         unsigned long i;
2361         u16 _rc, _rrc;
2362         int ret = 0;
2363
2364         /*
2365          * We ignore failures and try to destroy as many CPUs as possible.
2366          * At the same time we must not free the assigned resources when
2367          * this fails, as the ultravisor has still access to that memory.
2368          * So kvm_s390_pv_destroy_cpu can leave a "wanted" memory leak
2369          * behind.
2370          * We want to return the first failure rc and rrc, though.
2371          */
2372         kvm_for_each_vcpu(i, vcpu, kvm) {
2373                 mutex_lock(&vcpu->mutex);
2374                 if (kvm_s390_pv_destroy_cpu(vcpu, &_rc, &_rrc) && !ret) {
2375                         *rc = _rc;
2376                         *rrc = _rrc;
2377                         ret = -EIO;
2378                 }
2379                 mutex_unlock(&vcpu->mutex);
2380         }
2381         /* Ensure that we re-enable gisa if the non-PV guest used it but the PV guest did not. */
2382         if (use_gisa)
2383                 kvm_s390_gisa_enable(kvm);
2384         return ret;
2385 }
2386
2387 /**
2388  * kvm_s390_cpus_to_pv - Convert all non-protected vCPUs in a protected VM
2389  * to protected.
2390  * @kvm: the VM whose protected vCPUs are to be converted
2391  * @rc: return value for the RC field of the UVC (in case of error)
2392  * @rrc: return value for the RRC field of the UVC (in case of error)
2393  *
2394  * Tries to undo the conversion in case of error.
2395  *
2396  * Return: 0 in case of success, otherwise -EIO
2397  */
2398 static int kvm_s390_cpus_to_pv(struct kvm *kvm, u16 *rc, u16 *rrc)
2399 {
2400         unsigned long i;
2401         int r = 0;
2402         u16 dummy;
2403
2404         struct kvm_vcpu *vcpu;
2405
2406         /* Disable the GISA if the ultravisor does not support AIV. */
2407         if (!test_bit_inv(BIT_UV_FEAT_AIV, &uv_info.uv_feature_indications))
2408                 kvm_s390_gisa_disable(kvm);
2409
2410         kvm_for_each_vcpu(i, vcpu, kvm) {
2411                 mutex_lock(&vcpu->mutex);
2412                 r = kvm_s390_pv_create_cpu(vcpu, rc, rrc);
2413                 mutex_unlock(&vcpu->mutex);
2414                 if (r)
2415                         break;
2416         }
2417         if (r)
2418                 kvm_s390_cpus_from_pv(kvm, &dummy, &dummy);
2419         return r;
2420 }
2421
2422 /*
2423  * Here we provide user space with a direct interface to query UV
2424  * related data like UV maxima and available features as well as
2425  * feature specific data.
2426  *
2427  * To facilitate future extension of the data structures we'll try to
2428  * write data up to the maximum requested length.
2429  */
2430 static ssize_t kvm_s390_handle_pv_info(struct kvm_s390_pv_info *info)
2431 {
2432         ssize_t len_min;
2433
2434         switch (info->header.id) {
2435         case KVM_PV_INFO_VM: {
2436                 len_min =  sizeof(info->header) + sizeof(info->vm);
2437
2438                 if (info->header.len_max < len_min)
2439                         return -EINVAL;
2440
2441                 memcpy(info->vm.inst_calls_list,
2442                        uv_info.inst_calls_list,
2443                        sizeof(uv_info.inst_calls_list));
2444
2445                 /* It's max cpuid not max cpus, so it's off by one */
2446                 info->vm.max_cpus = uv_info.max_guest_cpu_id + 1;
2447                 info->vm.max_guests = uv_info.max_num_sec_conf;
2448                 info->vm.max_guest_addr = uv_info.max_sec_stor_addr;
2449                 info->vm.feature_indication = uv_info.uv_feature_indications;
2450
2451                 return len_min;
2452         }
2453         case KVM_PV_INFO_DUMP: {
2454                 len_min =  sizeof(info->header) + sizeof(info->dump);
2455
2456                 if (info->header.len_max < len_min)
2457                         return -EINVAL;
2458
2459                 info->dump.dump_cpu_buffer_len = uv_info.guest_cpu_stor_len;
2460                 info->dump.dump_config_mem_buffer_per_1m = uv_info.conf_dump_storage_state_len;
2461                 info->dump.dump_config_finalize_len = uv_info.conf_dump_finalize_len;
2462                 return len_min;
2463         }
2464         default:
2465                 return -EINVAL;
2466         }
2467 }
2468
2469 static int kvm_s390_pv_dmp(struct kvm *kvm, struct kvm_pv_cmd *cmd,
2470                            struct kvm_s390_pv_dmp dmp)
2471 {
2472         int r = -EINVAL;
2473         void __user *result_buff = (void __user *)dmp.buff_addr;
2474
2475         switch (dmp.subcmd) {
2476         case KVM_PV_DUMP_INIT: {
2477                 if (kvm->arch.pv.dumping)
2478                         break;
2479
2480                 /*
2481                  * Block SIE entry as concurrent dump UVCs could lead
2482                  * to validities.
2483                  */
2484                 kvm_s390_vcpu_block_all(kvm);
2485
2486                 r = uv_cmd_nodata(kvm_s390_pv_get_handle(kvm),
2487                                   UVC_CMD_DUMP_INIT, &cmd->rc, &cmd->rrc);
2488                 KVM_UV_EVENT(kvm, 3, "PROTVIRT DUMP INIT: rc %x rrc %x",
2489                              cmd->rc, cmd->rrc);
2490                 if (!r) {
2491                         kvm->arch.pv.dumping = true;
2492                 } else {
2493                         kvm_s390_vcpu_unblock_all(kvm);
2494                         r = -EINVAL;
2495                 }
2496                 break;
2497         }
2498         case KVM_PV_DUMP_CONFIG_STOR_STATE: {
2499                 if (!kvm->arch.pv.dumping)
2500                         break;
2501
2502                 /*
2503                  * gaddr is an output parameter since we might stop
2504                  * early. As dmp will be copied back in our caller, we
2505                  * don't need to do it ourselves.
2506                  */
2507                 r = kvm_s390_pv_dump_stor_state(kvm, result_buff, &dmp.gaddr, dmp.buff_len,
2508                                                 &cmd->rc, &cmd->rrc);
2509                 break;
2510         }
2511         case KVM_PV_DUMP_COMPLETE: {
2512                 if (!kvm->arch.pv.dumping)
2513                         break;
2514
2515                 r = -EINVAL;
2516                 if (dmp.buff_len < uv_info.conf_dump_finalize_len)
2517                         break;
2518
2519                 r = kvm_s390_pv_dump_complete(kvm, result_buff,
2520                                               &cmd->rc, &cmd->rrc);
2521                 break;
2522         }
2523         default:
2524                 r = -ENOTTY;
2525                 break;
2526         }
2527
2528         return r;
2529 }
2530
2531 static int kvm_s390_handle_pv(struct kvm *kvm, struct kvm_pv_cmd *cmd)
2532 {
2533         int r = 0;
2534         u16 dummy;
2535         void __user *argp = (void __user *)cmd->data;
2536
2537         switch (cmd->cmd) {
2538         case KVM_PV_ENABLE: {
2539                 r = -EINVAL;
2540                 if (kvm_s390_pv_is_protected(kvm))
2541                         break;
2542
2543                 /*
2544                  *  FMT 4 SIE needs esca. As we never switch back to bsca from
2545                  *  esca, we need no cleanup in the error cases below
2546                  */
2547                 r = sca_switch_to_extended(kvm);
2548                 if (r)
2549                         break;
2550
2551                 mmap_write_lock(current->mm);
2552                 r = gmap_mark_unmergeable();
2553                 mmap_write_unlock(current->mm);
2554                 if (r)
2555                         break;
2556
2557                 r = kvm_s390_pv_init_vm(kvm, &cmd->rc, &cmd->rrc);
2558                 if (r)
2559                         break;
2560
2561                 r = kvm_s390_cpus_to_pv(kvm, &cmd->rc, &cmd->rrc);
2562                 if (r)
2563                         kvm_s390_pv_deinit_vm(kvm, &dummy, &dummy);
2564
2565                 /* we need to block service interrupts from now on */
2566                 set_bit(IRQ_PEND_EXT_SERVICE, &kvm->arch.float_int.masked_irqs);
2567                 break;
2568         }
2569         case KVM_PV_DISABLE: {
2570                 r = -EINVAL;
2571                 if (!kvm_s390_pv_is_protected(kvm))
2572                         break;
2573
2574                 r = kvm_s390_cpus_from_pv(kvm, &cmd->rc, &cmd->rrc);
2575                 /*
2576                  * If a CPU could not be destroyed, destroy VM will also fail.
2577                  * There is no point in trying to destroy it. Instead return
2578                  * the rc and rrc from the first CPU that failed destroying.
2579                  */
2580                 if (r)
2581                         break;
2582                 r = kvm_s390_pv_deinit_vm(kvm, &cmd->rc, &cmd->rrc);
2583
2584                 /* no need to block service interrupts any more */
2585                 clear_bit(IRQ_PEND_EXT_SERVICE, &kvm->arch.float_int.masked_irqs);
2586                 break;
2587         }
2588         case KVM_PV_SET_SEC_PARMS: {
2589                 struct kvm_s390_pv_sec_parm parms = {};
2590                 void *hdr;
2591
2592                 r = -EINVAL;
2593                 if (!kvm_s390_pv_is_protected(kvm))
2594                         break;
2595
2596                 r = -EFAULT;
2597                 if (copy_from_user(&parms, argp, sizeof(parms)))
2598                         break;
2599
2600                 /* Currently restricted to 8KB */
2601                 r = -EINVAL;
2602                 if (parms.length > PAGE_SIZE * 2)
2603                         break;
2604
2605                 r = -ENOMEM;
2606                 hdr = vmalloc(parms.length);
2607                 if (!hdr)
2608                         break;
2609
2610                 r = -EFAULT;
2611                 if (!copy_from_user(hdr, (void __user *)parms.origin,
2612                                     parms.length))
2613                         r = kvm_s390_pv_set_sec_parms(kvm, hdr, parms.length,
2614                                                       &cmd->rc, &cmd->rrc);
2615
2616                 vfree(hdr);
2617                 break;
2618         }
2619         case KVM_PV_UNPACK: {
2620                 struct kvm_s390_pv_unp unp = {};
2621
2622                 r = -EINVAL;
2623                 if (!kvm_s390_pv_is_protected(kvm) || !mm_is_protected(kvm->mm))
2624                         break;
2625
2626                 r = -EFAULT;
2627                 if (copy_from_user(&unp, argp, sizeof(unp)))
2628                         break;
2629
2630                 r = kvm_s390_pv_unpack(kvm, unp.addr, unp.size, unp.tweak,
2631                                        &cmd->rc, &cmd->rrc);
2632                 break;
2633         }
2634         case KVM_PV_VERIFY: {
2635                 r = -EINVAL;
2636                 if (!kvm_s390_pv_is_protected(kvm))
2637                         break;
2638
2639                 r = uv_cmd_nodata(kvm_s390_pv_get_handle(kvm),
2640                                   UVC_CMD_VERIFY_IMG, &cmd->rc, &cmd->rrc);
2641                 KVM_UV_EVENT(kvm, 3, "PROTVIRT VERIFY: rc %x rrc %x", cmd->rc,
2642                              cmd->rrc);
2643                 break;
2644         }
2645         case KVM_PV_PREP_RESET: {
2646                 r = -EINVAL;
2647                 if (!kvm_s390_pv_is_protected(kvm))
2648                         break;
2649
2650                 r = uv_cmd_nodata(kvm_s390_pv_get_handle(kvm),
2651                                   UVC_CMD_PREPARE_RESET, &cmd->rc, &cmd->rrc);
2652                 KVM_UV_EVENT(kvm, 3, "PROTVIRT PREP RESET: rc %x rrc %x",
2653                              cmd->rc, cmd->rrc);
2654                 break;
2655         }
2656         case KVM_PV_UNSHARE_ALL: {
2657                 r = -EINVAL;
2658                 if (!kvm_s390_pv_is_protected(kvm))
2659                         break;
2660
2661                 r = uv_cmd_nodata(kvm_s390_pv_get_handle(kvm),
2662                                   UVC_CMD_SET_UNSHARE_ALL, &cmd->rc, &cmd->rrc);
2663                 KVM_UV_EVENT(kvm, 3, "PROTVIRT UNSHARE: rc %x rrc %x",
2664                              cmd->rc, cmd->rrc);
2665                 break;
2666         }
2667         case KVM_PV_INFO: {
2668                 struct kvm_s390_pv_info info = {};
2669                 ssize_t data_len;
2670
2671                 /*
2672                  * No need to check the VM protection here.
2673                  *
2674                  * Maybe user space wants to query some of the data
2675                  * when the VM is still unprotected. If we see the
2676                  * need to fence a new data command we can still
2677                  * return an error in the info handler.
2678                  */
2679
2680                 r = -EFAULT;
2681                 if (copy_from_user(&info, argp, sizeof(info.header)))
2682                         break;
2683
2684                 r = -EINVAL;
2685                 if (info.header.len_max < sizeof(info.header))
2686                         break;
2687
2688                 data_len = kvm_s390_handle_pv_info(&info);
2689                 if (data_len < 0) {
2690                         r = data_len;
2691                         break;
2692                 }
2693                 /*
2694                  * If a data command struct is extended (multiple
2695                  * times) this can be used to determine how much of it
2696                  * is valid.
2697                  */
2698                 info.header.len_written = data_len;
2699
2700                 r = -EFAULT;
2701                 if (copy_to_user(argp, &info, data_len))
2702                         break;
2703
2704                 r = 0;
2705                 break;
2706         }
2707         case KVM_PV_DUMP: {
2708                 struct kvm_s390_pv_dmp dmp;
2709
2710                 r = -EINVAL;
2711                 if (!kvm_s390_pv_is_protected(kvm))
2712                         break;
2713
2714                 r = -EFAULT;
2715                 if (copy_from_user(&dmp, argp, sizeof(dmp)))
2716                         break;
2717
2718                 r = kvm_s390_pv_dmp(kvm, cmd, dmp);
2719                 if (r)
2720                         break;
2721
2722                 if (copy_to_user(argp, &dmp, sizeof(dmp))) {
2723                         r = -EFAULT;
2724                         break;
2725                 }
2726
2727                 break;
2728         }
2729         default:
2730                 r = -ENOTTY;
2731         }
2732         return r;
2733 }
2734
2735 static bool access_key_invalid(u8 access_key)
2736 {
2737         return access_key > 0xf;
2738 }
2739
2740 static int kvm_s390_vm_mem_op(struct kvm *kvm, struct kvm_s390_mem_op *mop)
2741 {
2742         void __user *uaddr = (void __user *)mop->buf;
2743         u64 supported_flags;
2744         void *tmpbuf = NULL;
2745         int r, srcu_idx;
2746
2747         supported_flags = KVM_S390_MEMOP_F_SKEY_PROTECTION
2748                           | KVM_S390_MEMOP_F_CHECK_ONLY;
2749         if (mop->flags & ~supported_flags || !mop->size)
2750                 return -EINVAL;
2751         if (mop->size > MEM_OP_MAX_SIZE)
2752                 return -E2BIG;
2753         /*
2754          * This is technically a heuristic only, if the kvm->lock is not
2755          * taken, it is not guaranteed that the vm is/remains non-protected.
2756          * This is ok from a kernel perspective, wrongdoing is detected
2757          * on the access, -EFAULT is returned and the vm may crash the
2758          * next time it accesses the memory in question.
2759          * There is no sane usecase to do switching and a memop on two
2760          * different CPUs at the same time.
2761          */
2762         if (kvm_s390_pv_get_handle(kvm))
2763                 return -EINVAL;
2764         if (mop->flags & KVM_S390_MEMOP_F_SKEY_PROTECTION) {
2765                 if (access_key_invalid(mop->key))
2766                         return -EINVAL;
2767         } else {
2768                 mop->key = 0;
2769         }
2770         if (!(mop->flags & KVM_S390_MEMOP_F_CHECK_ONLY)) {
2771                 tmpbuf = vmalloc(mop->size);
2772                 if (!tmpbuf)
2773                         return -ENOMEM;
2774         }
2775
2776         srcu_idx = srcu_read_lock(&kvm->srcu);
2777
2778         if (kvm_is_error_gpa(kvm, mop->gaddr)) {
2779                 r = PGM_ADDRESSING;
2780                 goto out_unlock;
2781         }
2782
2783         switch (mop->op) {
2784         case KVM_S390_MEMOP_ABSOLUTE_READ: {
2785                 if (mop->flags & KVM_S390_MEMOP_F_CHECK_ONLY) {
2786                         r = check_gpa_range(kvm, mop->gaddr, mop->size, GACC_FETCH, mop->key);
2787                 } else {
2788                         r = access_guest_abs_with_key(kvm, mop->gaddr, tmpbuf,
2789                                                       mop->size, GACC_FETCH, mop->key);
2790                         if (r == 0) {
2791                                 if (copy_to_user(uaddr, tmpbuf, mop->size))
2792                                         r = -EFAULT;
2793                         }
2794                 }
2795                 break;
2796         }
2797         case KVM_S390_MEMOP_ABSOLUTE_WRITE: {
2798                 if (mop->flags & KVM_S390_MEMOP_F_CHECK_ONLY) {
2799                         r = check_gpa_range(kvm, mop->gaddr, mop->size, GACC_STORE, mop->key);
2800                 } else {
2801                         if (copy_from_user(tmpbuf, uaddr, mop->size)) {
2802                                 r = -EFAULT;
2803                                 break;
2804                         }
2805                         r = access_guest_abs_with_key(kvm, mop->gaddr, tmpbuf,
2806                                                       mop->size, GACC_STORE, mop->key);
2807                 }
2808                 break;
2809         }
2810         default:
2811                 r = -EINVAL;
2812         }
2813
2814 out_unlock:
2815         srcu_read_unlock(&kvm->srcu, srcu_idx);
2816
2817         vfree(tmpbuf);
2818         return r;
2819 }
2820
2821 long kvm_arch_vm_ioctl(struct file *filp,
2822                        unsigned int ioctl, unsigned long arg)
2823 {
2824         struct kvm *kvm = filp->private_data;
2825         void __user *argp = (void __user *)arg;
2826         struct kvm_device_attr attr;
2827         int r;
2828
2829         switch (ioctl) {
2830         case KVM_S390_INTERRUPT: {
2831                 struct kvm_s390_interrupt s390int;
2832
2833                 r = -EFAULT;
2834                 if (copy_from_user(&s390int, argp, sizeof(s390int)))
2835                         break;
2836                 r = kvm_s390_inject_vm(kvm, &s390int);
2837                 break;
2838         }
2839         case KVM_CREATE_IRQCHIP: {
2840                 struct kvm_irq_routing_entry routing;
2841
2842                 r = -EINVAL;
2843                 if (kvm->arch.use_irqchip) {
2844                         /* Set up dummy routing. */
2845                         memset(&routing, 0, sizeof(routing));
2846                         r = kvm_set_irq_routing(kvm, &routing, 0, 0);
2847                 }
2848                 break;
2849         }
2850         case KVM_SET_DEVICE_ATTR: {
2851                 r = -EFAULT;
2852                 if (copy_from_user(&attr, (void __user *)arg, sizeof(attr)))
2853                         break;
2854                 r = kvm_s390_vm_set_attr(kvm, &attr);
2855                 break;
2856         }
2857         case KVM_GET_DEVICE_ATTR: {
2858                 r = -EFAULT;
2859                 if (copy_from_user(&attr, (void __user *)arg, sizeof(attr)))
2860                         break;
2861                 r = kvm_s390_vm_get_attr(kvm, &attr);
2862                 break;
2863         }
2864         case KVM_HAS_DEVICE_ATTR: {
2865                 r = -EFAULT;
2866                 if (copy_from_user(&attr, (void __user *)arg, sizeof(attr)))
2867                         break;
2868                 r = kvm_s390_vm_has_attr(kvm, &attr);
2869                 break;
2870         }
2871         case KVM_S390_GET_SKEYS: {
2872                 struct kvm_s390_skeys args;
2873
2874                 r = -EFAULT;
2875                 if (copy_from_user(&args, argp,
2876                                    sizeof(struct kvm_s390_skeys)))
2877                         break;
2878                 r = kvm_s390_get_skeys(kvm, &args);
2879                 break;
2880         }
2881         case KVM_S390_SET_SKEYS: {
2882                 struct kvm_s390_skeys args;
2883
2884                 r = -EFAULT;
2885                 if (copy_from_user(&args, argp,
2886                                    sizeof(struct kvm_s390_skeys)))
2887                         break;
2888                 r = kvm_s390_set_skeys(kvm, &args);
2889                 break;
2890         }
2891         case KVM_S390_GET_CMMA_BITS: {
2892                 struct kvm_s390_cmma_log args;
2893
2894                 r = -EFAULT;
2895                 if (copy_from_user(&args, argp, sizeof(args)))
2896                         break;
2897                 mutex_lock(&kvm->slots_lock);
2898                 r = kvm_s390_get_cmma_bits(kvm, &args);
2899                 mutex_unlock(&kvm->slots_lock);
2900                 if (!r) {
2901                         r = copy_to_user(argp, &args, sizeof(args));
2902                         if (r)
2903                                 r = -EFAULT;
2904                 }
2905                 break;
2906         }
2907         case KVM_S390_SET_CMMA_BITS: {
2908                 struct kvm_s390_cmma_log args;
2909
2910                 r = -EFAULT;
2911                 if (copy_from_user(&args, argp, sizeof(args)))
2912                         break;
2913                 mutex_lock(&kvm->slots_lock);
2914                 r = kvm_s390_set_cmma_bits(kvm, &args);
2915                 mutex_unlock(&kvm->slots_lock);
2916                 break;
2917         }
2918         case KVM_S390_PV_COMMAND: {
2919                 struct kvm_pv_cmd args;
2920
2921                 /* protvirt means user cpu state */
2922                 kvm_s390_set_user_cpu_state_ctrl(kvm);
2923                 r = 0;
2924                 if (!is_prot_virt_host()) {
2925                         r = -EINVAL;
2926                         break;
2927                 }
2928                 if (copy_from_user(&args, argp, sizeof(args))) {
2929                         r = -EFAULT;
2930                         break;
2931                 }
2932                 if (args.flags) {
2933                         r = -EINVAL;
2934                         break;
2935                 }
2936                 mutex_lock(&kvm->lock);
2937                 r = kvm_s390_handle_pv(kvm, &args);
2938                 mutex_unlock(&kvm->lock);
2939                 if (copy_to_user(argp, &args, sizeof(args))) {
2940                         r = -EFAULT;
2941                         break;
2942                 }
2943                 break;
2944         }
2945         case KVM_S390_MEM_OP: {
2946                 struct kvm_s390_mem_op mem_op;
2947
2948                 if (copy_from_user(&mem_op, argp, sizeof(mem_op)) == 0)
2949                         r = kvm_s390_vm_mem_op(kvm, &mem_op);
2950                 else
2951                         r = -EFAULT;
2952                 break;
2953         }
2954         case KVM_S390_ZPCI_OP: {
2955                 struct kvm_s390_zpci_op args;
2956
2957                 r = -EINVAL;
2958                 if (!IS_ENABLED(CONFIG_VFIO_PCI_ZDEV_KVM))
2959                         break;
2960                 if (copy_from_user(&args, argp, sizeof(args))) {
2961                         r = -EFAULT;
2962                         break;
2963                 }
2964                 r = kvm_s390_pci_zpci_op(kvm, &args);
2965                 break;
2966         }
2967         default:
2968                 r = -ENOTTY;
2969         }
2970
2971         return r;
2972 }
2973
2974 static int kvm_s390_apxa_installed(void)
2975 {
2976         struct ap_config_info info;
2977
2978         if (ap_instructions_available()) {
2979                 if (ap_qci(&info) == 0)
2980                         return info.apxa;
2981         }
2982
2983         return 0;
2984 }
2985
2986 /*
2987  * The format of the crypto control block (CRYCB) is specified in the 3 low
2988  * order bits of the CRYCB designation (CRYCBD) field as follows:
2989  * Format 0: Neither the message security assist extension 3 (MSAX3) nor the
2990  *           AP extended addressing (APXA) facility are installed.
2991  * Format 1: The APXA facility is not installed but the MSAX3 facility is.
2992  * Format 2: Both the APXA and MSAX3 facilities are installed
2993  */
2994 static void kvm_s390_set_crycb_format(struct kvm *kvm)
2995 {
2996         kvm->arch.crypto.crycbd = (__u32)(unsigned long) kvm->arch.crypto.crycb;
2997
2998         /* Clear the CRYCB format bits - i.e., set format 0 by default */
2999         kvm->arch.crypto.crycbd &= ~(CRYCB_FORMAT_MASK);
3000
3001         /* Check whether MSAX3 is installed */
3002         if (!test_kvm_facility(kvm, 76))
3003                 return;
3004
3005         if (kvm_s390_apxa_installed())
3006                 kvm->arch.crypto.crycbd |= CRYCB_FORMAT2;
3007         else
3008                 kvm->arch.crypto.crycbd |= CRYCB_FORMAT1;
3009 }
3010
3011 /*
3012  * kvm_arch_crypto_set_masks
3013  *
3014  * @kvm: pointer to the target guest's KVM struct containing the crypto masks
3015  *       to be set.
3016  * @apm: the mask identifying the accessible AP adapters
3017  * @aqm: the mask identifying the accessible AP domains
3018  * @adm: the mask identifying the accessible AP control domains
3019  *
3020  * Set the masks that identify the adapters, domains and control domains to
3021  * which the KVM guest is granted access.
3022  *
3023  * Note: The kvm->lock mutex must be locked by the caller before invoking this
3024  *       function.
3025  */
3026 void kvm_arch_crypto_set_masks(struct kvm *kvm, unsigned long *apm,
3027                                unsigned long *aqm, unsigned long *adm)
3028 {
3029         struct kvm_s390_crypto_cb *crycb = kvm->arch.crypto.crycb;
3030
3031         kvm_s390_vcpu_block_all(kvm);
3032
3033         switch (kvm->arch.crypto.crycbd & CRYCB_FORMAT_MASK) {
3034         case CRYCB_FORMAT2: /* APCB1 use 256 bits */
3035                 memcpy(crycb->apcb1.apm, apm, 32);
3036                 VM_EVENT(kvm, 3, "SET CRYCB: apm %016lx %016lx %016lx %016lx",
3037                          apm[0], apm[1], apm[2], apm[3]);
3038                 memcpy(crycb->apcb1.aqm, aqm, 32);
3039                 VM_EVENT(kvm, 3, "SET CRYCB: aqm %016lx %016lx %016lx %016lx",
3040                          aqm[0], aqm[1], aqm[2], aqm[3]);
3041                 memcpy(crycb->apcb1.adm, adm, 32);
3042                 VM_EVENT(kvm, 3, "SET CRYCB: adm %016lx %016lx %016lx %016lx",
3043                          adm[0], adm[1], adm[2], adm[3]);
3044                 break;
3045         case CRYCB_FORMAT1:
3046         case CRYCB_FORMAT0: /* Fall through both use APCB0 */
3047                 memcpy(crycb->apcb0.apm, apm, 8);
3048                 memcpy(crycb->apcb0.aqm, aqm, 2);
3049                 memcpy(crycb->apcb0.adm, adm, 2);
3050                 VM_EVENT(kvm, 3, "SET CRYCB: apm %016lx aqm %04x adm %04x",
3051                          apm[0], *((unsigned short *)aqm),
3052                          *((unsigned short *)adm));
3053                 break;
3054         default:        /* Can not happen */
3055                 break;
3056         }
3057
3058         /* recreate the shadow crycb for each vcpu */
3059         kvm_s390_sync_request_broadcast(kvm, KVM_REQ_VSIE_RESTART);
3060         kvm_s390_vcpu_unblock_all(kvm);
3061 }
3062 EXPORT_SYMBOL_GPL(kvm_arch_crypto_set_masks);
3063
3064 /*
3065  * kvm_arch_crypto_clear_masks
3066  *
3067  * @kvm: pointer to the target guest's KVM struct containing the crypto masks
3068  *       to be cleared.
3069  *
3070  * Clear the masks that identify the adapters, domains and control domains to
3071  * which the KVM guest is granted access.
3072  *
3073  * Note: The kvm->lock mutex must be locked by the caller before invoking this
3074  *       function.
3075  */
3076 void kvm_arch_crypto_clear_masks(struct kvm *kvm)
3077 {
3078         kvm_s390_vcpu_block_all(kvm);
3079
3080         memset(&kvm->arch.crypto.crycb->apcb0, 0,
3081                sizeof(kvm->arch.crypto.crycb->apcb0));
3082         memset(&kvm->arch.crypto.crycb->apcb1, 0,
3083                sizeof(kvm->arch.crypto.crycb->apcb1));
3084
3085         VM_EVENT(kvm, 3, "%s", "CLR CRYCB:");
3086         /* recreate the shadow crycb for each vcpu */
3087         kvm_s390_sync_request_broadcast(kvm, KVM_REQ_VSIE_RESTART);
3088         kvm_s390_vcpu_unblock_all(kvm);
3089 }
3090 EXPORT_SYMBOL_GPL(kvm_arch_crypto_clear_masks);
3091
3092 static u64 kvm_s390_get_initial_cpuid(void)
3093 {
3094         struct cpuid cpuid;
3095
3096         get_cpu_id(&cpuid);
3097         cpuid.version = 0xff;
3098         return *((u64 *) &cpuid);
3099 }
3100
3101 static void kvm_s390_crypto_init(struct kvm *kvm)
3102 {
3103         kvm->arch.crypto.crycb = &kvm->arch.sie_page2->crycb;
3104         kvm_s390_set_crycb_format(kvm);
3105         init_rwsem(&kvm->arch.crypto.pqap_hook_rwsem);
3106
3107         if (!test_kvm_facility(kvm, 76))
3108                 return;
3109
3110         /* Enable AES/DEA protected key functions by default */
3111         kvm->arch.crypto.aes_kw = 1;
3112         kvm->arch.crypto.dea_kw = 1;
3113         get_random_bytes(kvm->arch.crypto.crycb->aes_wrapping_key_mask,
3114                          sizeof(kvm->arch.crypto.crycb->aes_wrapping_key_mask));
3115         get_random_bytes(kvm->arch.crypto.crycb->dea_wrapping_key_mask,
3116                          sizeof(kvm->arch.crypto.crycb->dea_wrapping_key_mask));
3117 }
3118
3119 static void sca_dispose(struct kvm *kvm)
3120 {
3121         if (kvm->arch.use_esca)
3122                 free_pages_exact(kvm->arch.sca, sizeof(struct esca_block));
3123         else
3124                 free_page((unsigned long)(kvm->arch.sca));
3125         kvm->arch.sca = NULL;
3126 }
3127
3128 void kvm_arch_free_vm(struct kvm *kvm)
3129 {
3130         if (IS_ENABLED(CONFIG_VFIO_PCI_ZDEV_KVM))
3131                 kvm_s390_pci_clear_list(kvm);
3132
3133         __kvm_arch_free_vm(kvm);
3134 }
3135
3136 int kvm_arch_init_vm(struct kvm *kvm, unsigned long type)
3137 {
3138         gfp_t alloc_flags = GFP_KERNEL_ACCOUNT;
3139         int i, rc;
3140         char debug_name[16];
3141         static unsigned long sca_offset;
3142
3143         rc = -EINVAL;
3144 #ifdef CONFIG_KVM_S390_UCONTROL
3145         if (type & ~KVM_VM_S390_UCONTROL)
3146                 goto out_err;
3147         if ((type & KVM_VM_S390_UCONTROL) && (!capable(CAP_SYS_ADMIN)))
3148                 goto out_err;
3149 #else
3150         if (type)
3151                 goto out_err;
3152 #endif
3153
3154         rc = s390_enable_sie();
3155         if (rc)
3156                 goto out_err;
3157
3158         rc = -ENOMEM;
3159
3160         if (!sclp.has_64bscao)
3161                 alloc_flags |= GFP_DMA;
3162         rwlock_init(&kvm->arch.sca_lock);
3163         /* start with basic SCA */
3164         kvm->arch.sca = (struct bsca_block *) get_zeroed_page(alloc_flags);
3165         if (!kvm->arch.sca)
3166                 goto out_err;
3167         mutex_lock(&kvm_lock);
3168         sca_offset += 16;
3169         if (sca_offset + sizeof(struct bsca_block) > PAGE_SIZE)
3170                 sca_offset = 0;
3171         kvm->arch.sca = (struct bsca_block *)
3172                         ((char *) kvm->arch.sca + sca_offset);
3173         mutex_unlock(&kvm_lock);
3174
3175         sprintf(debug_name, "kvm-%u", current->pid);
3176
3177         kvm->arch.dbf = debug_register(debug_name, 32, 1, 7 * sizeof(long));
3178         if (!kvm->arch.dbf)
3179                 goto out_err;
3180
3181         BUILD_BUG_ON(sizeof(struct sie_page2) != 4096);
3182         kvm->arch.sie_page2 =
3183              (struct sie_page2 *) get_zeroed_page(GFP_KERNEL_ACCOUNT | GFP_DMA);
3184         if (!kvm->arch.sie_page2)
3185                 goto out_err;
3186
3187         kvm->arch.sie_page2->kvm = kvm;
3188         kvm->arch.model.fac_list = kvm->arch.sie_page2->fac_list;
3189
3190         for (i = 0; i < kvm_s390_fac_size(); i++) {
3191                 kvm->arch.model.fac_mask[i] = stfle_fac_list[i] &
3192                                               (kvm_s390_fac_base[i] |
3193                                                kvm_s390_fac_ext[i]);
3194                 kvm->arch.model.fac_list[i] = stfle_fac_list[i] &
3195                                               kvm_s390_fac_base[i];
3196         }
3197         kvm->arch.model.subfuncs = kvm_s390_available_subfunc;
3198
3199         /* we are always in czam mode - even on pre z14 machines */
3200         set_kvm_facility(kvm->arch.model.fac_mask, 138);
3201         set_kvm_facility(kvm->arch.model.fac_list, 138);
3202         /* we emulate STHYI in kvm */
3203         set_kvm_facility(kvm->arch.model.fac_mask, 74);
3204         set_kvm_facility(kvm->arch.model.fac_list, 74);
3205         if (MACHINE_HAS_TLB_GUEST) {
3206                 set_kvm_facility(kvm->arch.model.fac_mask, 147);
3207                 set_kvm_facility(kvm->arch.model.fac_list, 147);
3208         }
3209
3210         if (css_general_characteristics.aiv && test_facility(65))
3211                 set_kvm_facility(kvm->arch.model.fac_mask, 65);
3212
3213         kvm->arch.model.cpuid = kvm_s390_get_initial_cpuid();
3214         kvm->arch.model.ibc = sclp.ibc & 0x0fff;
3215
3216         kvm_s390_crypto_init(kvm);
3217
3218         if (IS_ENABLED(CONFIG_VFIO_PCI_ZDEV_KVM)) {
3219                 mutex_lock(&kvm->lock);
3220                 kvm_s390_pci_init_list(kvm);
3221                 kvm_s390_vcpu_pci_enable_interp(kvm);
3222                 mutex_unlock(&kvm->lock);
3223         }
3224
3225         mutex_init(&kvm->arch.float_int.ais_lock);
3226         spin_lock_init(&kvm->arch.float_int.lock);
3227         for (i = 0; i < FIRQ_LIST_COUNT; i++)
3228                 INIT_LIST_HEAD(&kvm->arch.float_int.lists[i]);
3229         init_waitqueue_head(&kvm->arch.ipte_wq);
3230         mutex_init(&kvm->arch.ipte_mutex);
3231
3232         debug_register_view(kvm->arch.dbf, &debug_sprintf_view);
3233         VM_EVENT(kvm, 3, "vm created with type %lu", type);
3234
3235         if (type & KVM_VM_S390_UCONTROL) {
3236                 kvm->arch.gmap = NULL;
3237                 kvm->arch.mem_limit = KVM_S390_NO_MEM_LIMIT;
3238         } else {
3239                 if (sclp.hamax == U64_MAX)
3240                         kvm->arch.mem_limit = TASK_SIZE_MAX;
3241                 else
3242                         kvm->arch.mem_limit = min_t(unsigned long, TASK_SIZE_MAX,
3243                                                     sclp.hamax + 1);
3244                 kvm->arch.gmap = gmap_create(current->mm, kvm->arch.mem_limit - 1);
3245                 if (!kvm->arch.gmap)
3246                         goto out_err;
3247                 kvm->arch.gmap->private = kvm;
3248                 kvm->arch.gmap->pfault_enabled = 0;
3249         }
3250
3251         kvm->arch.use_pfmfi = sclp.has_pfmfi;
3252         kvm->arch.use_skf = sclp.has_skey;
3253         spin_lock_init(&kvm->arch.start_stop_lock);
3254         kvm_s390_vsie_init(kvm);
3255         if (use_gisa)
3256                 kvm_s390_gisa_init(kvm);
3257         KVM_EVENT(3, "vm 0x%pK created by pid %u", kvm, current->pid);
3258
3259         return 0;
3260 out_err:
3261         free_page((unsigned long)kvm->arch.sie_page2);
3262         debug_unregister(kvm->arch.dbf);
3263         sca_dispose(kvm);
3264         KVM_EVENT(3, "creation of vm failed: %d", rc);
3265         return rc;
3266 }
3267
3268 void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
3269 {
3270         u16 rc, rrc;
3271
3272         VCPU_EVENT(vcpu, 3, "%s", "free cpu");
3273         trace_kvm_s390_destroy_vcpu(vcpu->vcpu_id);
3274         kvm_s390_clear_local_irqs(vcpu);
3275         kvm_clear_async_pf_completion_queue(vcpu);
3276         if (!kvm_is_ucontrol(vcpu->kvm))
3277                 sca_del_vcpu(vcpu);
3278         kvm_s390_update_topology_change_report(vcpu->kvm, 1);
3279
3280         if (kvm_is_ucontrol(vcpu->kvm))
3281                 gmap_remove(vcpu->arch.gmap);
3282
3283         if (vcpu->kvm->arch.use_cmma)
3284                 kvm_s390_vcpu_unsetup_cmma(vcpu);
3285         /* We can not hold the vcpu mutex here, we are already dying */
3286         if (kvm_s390_pv_cpu_get_handle(vcpu))
3287                 kvm_s390_pv_destroy_cpu(vcpu, &rc, &rrc);
3288         free_page((unsigned long)(vcpu->arch.sie_block));
3289 }
3290
3291 void kvm_arch_destroy_vm(struct kvm *kvm)
3292 {
3293         u16 rc, rrc;
3294
3295         kvm_destroy_vcpus(kvm);
3296         sca_dispose(kvm);
3297         kvm_s390_gisa_destroy(kvm);
3298         /*
3299          * We are already at the end of life and kvm->lock is not taken.
3300          * This is ok as the file descriptor is closed by now and nobody
3301          * can mess with the pv state. To avoid lockdep_assert_held from
3302          * complaining we do not use kvm_s390_pv_is_protected.
3303          */
3304         if (kvm_s390_pv_get_handle(kvm))
3305                 kvm_s390_pv_deinit_vm(kvm, &rc, &rrc);
3306         /*
3307          * Remove the mmu notifier only when the whole KVM VM is torn down,
3308          * and only if one was registered to begin with. If the VM is
3309          * currently not protected, but has been previously been protected,
3310          * then it's possible that the notifier is still registered.
3311          */
3312         if (kvm->arch.pv.mmu_notifier.ops)
3313                 mmu_notifier_unregister(&kvm->arch.pv.mmu_notifier, kvm->mm);
3314
3315         debug_unregister(kvm->arch.dbf);
3316         free_page((unsigned long)kvm->arch.sie_page2);
3317         if (!kvm_is_ucontrol(kvm))
3318                 gmap_remove(kvm->arch.gmap);
3319         kvm_s390_destroy_adapters(kvm);
3320         kvm_s390_clear_float_irqs(kvm);
3321         kvm_s390_vsie_destroy(kvm);
3322         KVM_EVENT(3, "vm 0x%pK destroyed", kvm);
3323 }
3324
3325 /* Section: vcpu related */
3326 static int __kvm_ucontrol_vcpu_init(struct kvm_vcpu *vcpu)
3327 {
3328         vcpu->arch.gmap = gmap_create(current->mm, -1UL);
3329         if (!vcpu->arch.gmap)
3330                 return -ENOMEM;
3331         vcpu->arch.gmap->private = vcpu->kvm;
3332
3333         return 0;
3334 }
3335
3336 static void sca_del_vcpu(struct kvm_vcpu *vcpu)
3337 {
3338         if (!kvm_s390_use_sca_entries())
3339                 return;
3340         read_lock(&vcpu->kvm->arch.sca_lock);
3341         if (vcpu->kvm->arch.use_esca) {
3342                 struct esca_block *sca = vcpu->kvm->arch.sca;
3343
3344                 clear_bit_inv(vcpu->vcpu_id, (unsigned long *) sca->mcn);
3345                 sca->cpu[vcpu->vcpu_id].sda = 0;
3346         } else {
3347                 struct bsca_block *sca = vcpu->kvm->arch.sca;
3348
3349                 clear_bit_inv(vcpu->vcpu_id, (unsigned long *) &sca->mcn);
3350                 sca->cpu[vcpu->vcpu_id].sda = 0;
3351         }
3352         read_unlock(&vcpu->kvm->arch.sca_lock);
3353 }
3354
3355 static void sca_add_vcpu(struct kvm_vcpu *vcpu)
3356 {
3357         if (!kvm_s390_use_sca_entries()) {
3358                 struct bsca_block *sca = vcpu->kvm->arch.sca;
3359
3360                 /* we still need the basic sca for the ipte control */
3361                 vcpu->arch.sie_block->scaoh = (__u32)(((__u64)sca) >> 32);
3362                 vcpu->arch.sie_block->scaol = (__u32)(__u64)sca;
3363                 return;
3364         }
3365         read_lock(&vcpu->kvm->arch.sca_lock);
3366         if (vcpu->kvm->arch.use_esca) {
3367                 struct esca_block *sca = vcpu->kvm->arch.sca;
3368
3369                 sca->cpu[vcpu->vcpu_id].sda = (__u64) vcpu->arch.sie_block;
3370                 vcpu->arch.sie_block->scaoh = (__u32)(((__u64)sca) >> 32);
3371                 vcpu->arch.sie_block->scaol = (__u32)(__u64)sca & ~0x3fU;
3372                 vcpu->arch.sie_block->ecb2 |= ECB2_ESCA;
3373                 set_bit_inv(vcpu->vcpu_id, (unsigned long *) sca->mcn);
3374         } else {
3375                 struct bsca_block *sca = vcpu->kvm->arch.sca;
3376
3377                 sca->cpu[vcpu->vcpu_id].sda = (__u64) vcpu->arch.sie_block;
3378                 vcpu->arch.sie_block->scaoh = (__u32)(((__u64)sca) >> 32);
3379                 vcpu->arch.sie_block->scaol = (__u32)(__u64)sca;
3380                 set_bit_inv(vcpu->vcpu_id, (unsigned long *) &sca->mcn);
3381         }
3382         read_unlock(&vcpu->kvm->arch.sca_lock);
3383 }
3384
3385 /* Basic SCA to Extended SCA data copy routines */
3386 static inline void sca_copy_entry(struct esca_entry *d, struct bsca_entry *s)
3387 {
3388         d->sda = s->sda;
3389         d->sigp_ctrl.c = s->sigp_ctrl.c;
3390         d->sigp_ctrl.scn = s->sigp_ctrl.scn;
3391 }
3392
3393 static void sca_copy_b_to_e(struct esca_block *d, struct bsca_block *s)
3394 {
3395         int i;
3396
3397         d->ipte_control = s->ipte_control;
3398         d->mcn[0] = s->mcn;
3399         for (i = 0; i < KVM_S390_BSCA_CPU_SLOTS; i++)
3400                 sca_copy_entry(&d->cpu[i], &s->cpu[i]);
3401 }
3402
3403 static int sca_switch_to_extended(struct kvm *kvm)
3404 {
3405         struct bsca_block *old_sca = kvm->arch.sca;
3406         struct esca_block *new_sca;
3407         struct kvm_vcpu *vcpu;
3408         unsigned long vcpu_idx;
3409         u32 scaol, scaoh;
3410
3411         if (kvm->arch.use_esca)
3412                 return 0;
3413
3414         new_sca = alloc_pages_exact(sizeof(*new_sca), GFP_KERNEL_ACCOUNT | __GFP_ZERO);
3415         if (!new_sca)
3416                 return -ENOMEM;
3417
3418         scaoh = (u32)((u64)(new_sca) >> 32);
3419         scaol = (u32)(u64)(new_sca) & ~0x3fU;
3420
3421         kvm_s390_vcpu_block_all(kvm);
3422         write_lock(&kvm->arch.sca_lock);
3423
3424         sca_copy_b_to_e(new_sca, old_sca);
3425
3426         kvm_for_each_vcpu(vcpu_idx, vcpu, kvm) {
3427                 vcpu->arch.sie_block->scaoh = scaoh;
3428                 vcpu->arch.sie_block->scaol = scaol;
3429                 vcpu->arch.sie_block->ecb2 |= ECB2_ESCA;
3430         }
3431         kvm->arch.sca = new_sca;
3432         kvm->arch.use_esca = 1;
3433
3434         write_unlock(&kvm->arch.sca_lock);
3435         kvm_s390_vcpu_unblock_all(kvm);
3436
3437         free_page((unsigned long)old_sca);
3438
3439         VM_EVENT(kvm, 2, "Switched to ESCA (0x%pK -> 0x%pK)",
3440                  old_sca, kvm->arch.sca);
3441         return 0;
3442 }
3443
3444 static int sca_can_add_vcpu(struct kvm *kvm, unsigned int id)
3445 {
3446         int rc;
3447
3448         if (!kvm_s390_use_sca_entries()) {
3449                 if (id < KVM_MAX_VCPUS)
3450                         return true;
3451                 return false;
3452         }
3453         if (id < KVM_S390_BSCA_CPU_SLOTS)
3454                 return true;
3455         if (!sclp.has_esca || !sclp.has_64bscao)
3456                 return false;
3457
3458         rc = kvm->arch.use_esca ? 0 : sca_switch_to_extended(kvm);
3459
3460         return rc == 0 && id < KVM_S390_ESCA_CPU_SLOTS;
3461 }
3462
3463 /* needs disabled preemption to protect from TOD sync and vcpu_load/put */
3464 static void __start_cpu_timer_accounting(struct kvm_vcpu *vcpu)
3465 {
3466         WARN_ON_ONCE(vcpu->arch.cputm_start != 0);
3467         raw_write_seqcount_begin(&vcpu->arch.cputm_seqcount);
3468         vcpu->arch.cputm_start = get_tod_clock_fast();
3469         raw_write_seqcount_end(&vcpu->arch.cputm_seqcount);
3470 }
3471
3472 /* needs disabled preemption to protect from TOD sync and vcpu_load/put */
3473 static void __stop_cpu_timer_accounting(struct kvm_vcpu *vcpu)
3474 {
3475         WARN_ON_ONCE(vcpu->arch.cputm_start == 0);
3476         raw_write_seqcount_begin(&vcpu->arch.cputm_seqcount);
3477         vcpu->arch.sie_block->cputm -= get_tod_clock_fast() - vcpu->arch.cputm_start;
3478         vcpu->arch.cputm_start = 0;
3479         raw_write_seqcount_end(&vcpu->arch.cputm_seqcount);
3480 }
3481
3482 /* needs disabled preemption to protect from TOD sync and vcpu_load/put */
3483 static void __enable_cpu_timer_accounting(struct kvm_vcpu *vcpu)
3484 {
3485         WARN_ON_ONCE(vcpu->arch.cputm_enabled);
3486         vcpu->arch.cputm_enabled = true;
3487         __start_cpu_timer_accounting(vcpu);
3488 }
3489
3490 /* needs disabled preemption to protect from TOD sync and vcpu_load/put */
3491 static void __disable_cpu_timer_accounting(struct kvm_vcpu *vcpu)
3492 {
3493         WARN_ON_ONCE(!vcpu->arch.cputm_enabled);
3494         __stop_cpu_timer_accounting(vcpu);
3495         vcpu->arch.cputm_enabled = false;
3496 }
3497
3498 static void enable_cpu_timer_accounting(struct kvm_vcpu *vcpu)
3499 {
3500         preempt_disable(); /* protect from TOD sync and vcpu_load/put */
3501         __enable_cpu_timer_accounting(vcpu);
3502         preempt_enable();
3503 }
3504
3505 static void disable_cpu_timer_accounting(struct kvm_vcpu *vcpu)
3506 {
3507         preempt_disable(); /* protect from TOD sync and vcpu_load/put */
3508         __disable_cpu_timer_accounting(vcpu);
3509         preempt_enable();
3510 }
3511
3512 /* set the cpu timer - may only be called from the VCPU thread itself */
3513 void kvm_s390_set_cpu_timer(struct kvm_vcpu *vcpu, __u64 cputm)
3514 {
3515         preempt_disable(); /* protect from TOD sync and vcpu_load/put */
3516         raw_write_seqcount_begin(&vcpu->arch.cputm_seqcount);
3517         if (vcpu->arch.cputm_enabled)
3518                 vcpu->arch.cputm_start = get_tod_clock_fast();
3519         vcpu->arch.sie_block->cputm = cputm;
3520         raw_write_seqcount_end(&vcpu->arch.cputm_seqcount);
3521         preempt_enable();
3522 }
3523
3524 /* update and get the cpu timer - can also be called from other VCPU threads */
3525 __u64 kvm_s390_get_cpu_timer(struct kvm_vcpu *vcpu)
3526 {
3527         unsigned int seq;
3528         __u64 value;
3529
3530         if (unlikely(!vcpu->arch.cputm_enabled))
3531                 return vcpu->arch.sie_block->cputm;
3532
3533         preempt_disable(); /* protect from TOD sync and vcpu_load/put */
3534         do {
3535                 seq = raw_read_seqcount(&vcpu->arch.cputm_seqcount);
3536                 /*
3537                  * If the writer would ever execute a read in the critical
3538                  * section, e.g. in irq context, we have a deadlock.
3539                  */
3540                 WARN_ON_ONCE((seq & 1) && smp_processor_id() == vcpu->cpu);
3541                 value = vcpu->arch.sie_block->cputm;
3542                 /* if cputm_start is 0, accounting is being started/stopped */
3543                 if (likely(vcpu->arch.cputm_start))
3544                         value -= get_tod_clock_fast() - vcpu->arch.cputm_start;
3545         } while (read_seqcount_retry(&vcpu->arch.cputm_seqcount, seq & ~1));
3546         preempt_enable();
3547         return value;
3548 }
3549
3550 void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
3551 {
3552
3553         gmap_enable(vcpu->arch.enabled_gmap);
3554         kvm_s390_set_cpuflags(vcpu, CPUSTAT_RUNNING);
3555         if (vcpu->arch.cputm_enabled && !is_vcpu_idle(vcpu))
3556                 __start_cpu_timer_accounting(vcpu);
3557         vcpu->cpu = cpu;
3558 }
3559
3560 void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
3561 {
3562         vcpu->cpu = -1;
3563         if (vcpu->arch.cputm_enabled && !is_vcpu_idle(vcpu))
3564                 __stop_cpu_timer_accounting(vcpu);
3565         kvm_s390_clear_cpuflags(vcpu, CPUSTAT_RUNNING);
3566         vcpu->arch.enabled_gmap = gmap_get_enabled();
3567         gmap_disable(vcpu->arch.enabled_gmap);
3568
3569 }
3570
3571 void kvm_arch_vcpu_postcreate(struct kvm_vcpu *vcpu)
3572 {
3573         mutex_lock(&vcpu->kvm->lock);
3574         preempt_disable();
3575         vcpu->arch.sie_block->epoch = vcpu->kvm->arch.epoch;
3576         vcpu->arch.sie_block->epdx = vcpu->kvm->arch.epdx;
3577         preempt_enable();
3578         mutex_unlock(&vcpu->kvm->lock);
3579         if (!kvm_is_ucontrol(vcpu->kvm)) {
3580                 vcpu->arch.gmap = vcpu->kvm->arch.gmap;
3581                 sca_add_vcpu(vcpu);
3582         }
3583         if (test_kvm_facility(vcpu->kvm, 74) || vcpu->kvm->arch.user_instr0)
3584                 vcpu->arch.sie_block->ictl |= ICTL_OPEREXC;
3585         /* make vcpu_load load the right gmap on the first trigger */
3586         vcpu->arch.enabled_gmap = vcpu->arch.gmap;
3587 }
3588
3589 static bool kvm_has_pckmo_subfunc(struct kvm *kvm, unsigned long nr)
3590 {
3591         if (test_bit_inv(nr, (unsigned long *)&kvm->arch.model.subfuncs.pckmo) &&
3592             test_bit_inv(nr, (unsigned long *)&kvm_s390_available_subfunc.pckmo))
3593                 return true;
3594         return false;
3595 }
3596
3597 static bool kvm_has_pckmo_ecc(struct kvm *kvm)
3598 {
3599         /* At least one ECC subfunction must be present */
3600         return kvm_has_pckmo_subfunc(kvm, 32) ||
3601                kvm_has_pckmo_subfunc(kvm, 33) ||
3602                kvm_has_pckmo_subfunc(kvm, 34) ||
3603                kvm_has_pckmo_subfunc(kvm, 40) ||
3604                kvm_has_pckmo_subfunc(kvm, 41);
3605
3606 }
3607
3608 static void kvm_s390_vcpu_crypto_setup(struct kvm_vcpu *vcpu)
3609 {
3610         /*
3611          * If the AP instructions are not being interpreted and the MSAX3
3612          * facility is not configured for the guest, there is nothing to set up.
3613          */
3614         if (!vcpu->kvm->arch.crypto.apie && !test_kvm_facility(vcpu->kvm, 76))
3615                 return;
3616
3617         vcpu->arch.sie_block->crycbd = vcpu->kvm->arch.crypto.crycbd;
3618         vcpu->arch.sie_block->ecb3 &= ~(ECB3_AES | ECB3_DEA);
3619         vcpu->arch.sie_block->eca &= ~ECA_APIE;
3620         vcpu->arch.sie_block->ecd &= ~ECD_ECC;
3621
3622         if (vcpu->kvm->arch.crypto.apie)
3623                 vcpu->arch.sie_block->eca |= ECA_APIE;
3624
3625         /* Set up protected key support */
3626         if (vcpu->kvm->arch.crypto.aes_kw) {
3627                 vcpu->arch.sie_block->ecb3 |= ECB3_AES;
3628                 /* ecc is also wrapped with AES key */
3629                 if (kvm_has_pckmo_ecc(vcpu->kvm))
3630                         vcpu->arch.sie_block->ecd |= ECD_ECC;
3631         }
3632
3633         if (vcpu->kvm->arch.crypto.dea_kw)
3634                 vcpu->arch.sie_block->ecb3 |= ECB3_DEA;
3635 }
3636
3637 void kvm_s390_vcpu_unsetup_cmma(struct kvm_vcpu *vcpu)
3638 {
3639         free_page(vcpu->arch.sie_block->cbrlo);
3640         vcpu->arch.sie_block->cbrlo = 0;
3641 }
3642
3643 int kvm_s390_vcpu_setup_cmma(struct kvm_vcpu *vcpu)
3644 {
3645         vcpu->arch.sie_block->cbrlo = get_zeroed_page(GFP_KERNEL_ACCOUNT);
3646         if (!vcpu->arch.sie_block->cbrlo)
3647                 return -ENOMEM;
3648         return 0;
3649 }
3650
3651 static void kvm_s390_vcpu_setup_model(struct kvm_vcpu *vcpu)
3652 {
3653         struct kvm_s390_cpu_model *model = &vcpu->kvm->arch.model;
3654
3655         vcpu->arch.sie_block->ibc = model->ibc;
3656         if (test_kvm_facility(vcpu->kvm, 7))
3657                 vcpu->arch.sie_block->fac = (u32)(u64) model->fac_list;
3658 }
3659
3660 static int kvm_s390_vcpu_setup(struct kvm_vcpu *vcpu)
3661 {
3662         int rc = 0;
3663         u16 uvrc, uvrrc;
3664
3665         atomic_set(&vcpu->arch.sie_block->cpuflags, CPUSTAT_ZARCH |
3666                                                     CPUSTAT_SM |
3667                                                     CPUSTAT_STOPPED);
3668
3669         if (test_kvm_facility(vcpu->kvm, 78))
3670                 kvm_s390_set_cpuflags(vcpu, CPUSTAT_GED2);
3671         else if (test_kvm_facility(vcpu->kvm, 8))
3672                 kvm_s390_set_cpuflags(vcpu, CPUSTAT_GED);
3673
3674         kvm_s390_vcpu_setup_model(vcpu);
3675
3676         /* pgste_set_pte has special handling for !MACHINE_HAS_ESOP */
3677         if (MACHINE_HAS_ESOP)
3678                 vcpu->arch.sie_block->ecb |= ECB_HOSTPROTINT;
3679         if (test_kvm_facility(vcpu->kvm, 9))
3680                 vcpu->arch.sie_block->ecb |= ECB_SRSI;
3681         if (test_kvm_facility(vcpu->kvm, 11))
3682                 vcpu->arch.sie_block->ecb |= ECB_PTF;
3683         if (test_kvm_facility(vcpu->kvm, 73))
3684                 vcpu->arch.sie_block->ecb |= ECB_TE;
3685         if (!kvm_is_ucontrol(vcpu->kvm))
3686                 vcpu->arch.sie_block->ecb |= ECB_SPECI;
3687
3688         if (test_kvm_facility(vcpu->kvm, 8) && vcpu->kvm->arch.use_pfmfi)
3689                 vcpu->arch.sie_block->ecb2 |= ECB2_PFMFI;
3690         if (test_kvm_facility(vcpu->kvm, 130))
3691                 vcpu->arch.sie_block->ecb2 |= ECB2_IEP;
3692         vcpu->arch.sie_block->eca = ECA_MVPGI | ECA_PROTEXCI;
3693         if (sclp.has_cei)
3694                 vcpu->arch.sie_block->eca |= ECA_CEI;
3695         if (sclp.has_ib)
3696                 vcpu->arch.sie_block->eca |= ECA_IB;
3697         if (sclp.has_siif)
3698                 vcpu->arch.sie_block->eca |= ECA_SII;
3699         if (sclp.has_sigpif)
3700                 vcpu->arch.sie_block->eca |= ECA_SIGPI;
3701         if (test_kvm_facility(vcpu->kvm, 129)) {
3702                 vcpu->arch.sie_block->eca |= ECA_VX;
3703                 vcpu->arch.sie_block->ecd |= ECD_HOSTREGMGMT;
3704         }
3705         if (test_kvm_facility(vcpu->kvm, 139))
3706                 vcpu->arch.sie_block->ecd |= ECD_MEF;
3707         if (test_kvm_facility(vcpu->kvm, 156))
3708                 vcpu->arch.sie_block->ecd |= ECD_ETOKENF;
3709         if (vcpu->arch.sie_block->gd) {
3710                 vcpu->arch.sie_block->eca |= ECA_AIV;
3711                 VCPU_EVENT(vcpu, 3, "AIV gisa format-%u enabled for cpu %03u",
3712                            vcpu->arch.sie_block->gd & 0x3, vcpu->vcpu_id);
3713         }
3714         vcpu->arch.sie_block->sdnxo = ((unsigned long) &vcpu->run->s.regs.sdnx)
3715                                         | SDNXC;
3716         vcpu->arch.sie_block->riccbd = (unsigned long) &vcpu->run->s.regs.riccb;
3717
3718         if (sclp.has_kss)
3719                 kvm_s390_set_cpuflags(vcpu, CPUSTAT_KSS);
3720         else
3721                 vcpu->arch.sie_block->ictl |= ICTL_ISKE | ICTL_SSKE | ICTL_RRBE;
3722
3723         if (vcpu->kvm->arch.use_cmma) {
3724                 rc = kvm_s390_vcpu_setup_cmma(vcpu);
3725                 if (rc)
3726                         return rc;
3727         }
3728         hrtimer_init(&vcpu->arch.ckc_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
3729         vcpu->arch.ckc_timer.function = kvm_s390_idle_wakeup;
3730
3731         vcpu->arch.sie_block->hpid = HPID_KVM;
3732
3733         kvm_s390_vcpu_crypto_setup(vcpu);
3734
3735         kvm_s390_vcpu_pci_setup(vcpu);
3736
3737         mutex_lock(&vcpu->kvm->lock);
3738         if (kvm_s390_pv_is_protected(vcpu->kvm)) {
3739                 rc = kvm_s390_pv_create_cpu(vcpu, &uvrc, &uvrrc);
3740                 if (rc)
3741                         kvm_s390_vcpu_unsetup_cmma(vcpu);
3742         }
3743         mutex_unlock(&vcpu->kvm->lock);
3744
3745         return rc;
3746 }
3747
3748 int kvm_arch_vcpu_precreate(struct kvm *kvm, unsigned int id)
3749 {
3750         if (!kvm_is_ucontrol(kvm) && !sca_can_add_vcpu(kvm, id))
3751                 return -EINVAL;
3752         return 0;
3753 }
3754
3755 int kvm_arch_vcpu_create(struct kvm_vcpu *vcpu)
3756 {
3757         struct sie_page *sie_page;
3758         int rc;
3759
3760         BUILD_BUG_ON(sizeof(struct sie_page) != 4096);
3761         sie_page = (struct sie_page *) get_zeroed_page(GFP_KERNEL_ACCOUNT);
3762         if (!sie_page)
3763                 return -ENOMEM;
3764
3765         vcpu->arch.sie_block = &sie_page->sie_block;
3766         vcpu->arch.sie_block->itdba = (unsigned long) &sie_page->itdb;
3767
3768         /* the real guest size will always be smaller than msl */
3769         vcpu->arch.sie_block->mso = 0;
3770         vcpu->arch.sie_block->msl = sclp.hamax;
3771
3772         vcpu->arch.sie_block->icpua = vcpu->vcpu_id;
3773         spin_lock_init(&vcpu->arch.local_int.lock);
3774         vcpu->arch.sie_block->gd = kvm_s390_get_gisa_desc(vcpu->kvm);
3775         seqcount_init(&vcpu->arch.cputm_seqcount);
3776
3777         vcpu->arch.pfault_token = KVM_S390_PFAULT_TOKEN_INVALID;
3778         kvm_clear_async_pf_completion_queue(vcpu);
3779         vcpu->run->kvm_valid_regs = KVM_SYNC_PREFIX |
3780                                     KVM_SYNC_GPRS |
3781                                     KVM_SYNC_ACRS |
3782                                     KVM_SYNC_CRS |
3783                                     KVM_SYNC_ARCH0 |
3784                                     KVM_SYNC_PFAULT |
3785                                     KVM_SYNC_DIAG318;
3786         kvm_s390_set_prefix(vcpu, 0);
3787         if (test_kvm_facility(vcpu->kvm, 64))
3788                 vcpu->run->kvm_valid_regs |= KVM_SYNC_RICCB;
3789         if (test_kvm_facility(vcpu->kvm, 82))
3790                 vcpu->run->kvm_valid_regs |= KVM_SYNC_BPBC;
3791         if (test_kvm_facility(vcpu->kvm, 133))
3792                 vcpu->run->kvm_valid_regs |= KVM_SYNC_GSCB;
3793         if (test_kvm_facility(vcpu->kvm, 156))
3794                 vcpu->run->kvm_valid_regs |= KVM_SYNC_ETOKEN;
3795         /* fprs can be synchronized via vrs, even if the guest has no vx. With
3796          * MACHINE_HAS_VX, (load|store)_fpu_regs() will work with vrs format.
3797          */
3798         if (MACHINE_HAS_VX)
3799                 vcpu->run->kvm_valid_regs |= KVM_SYNC_VRS;
3800         else
3801                 vcpu->run->kvm_valid_regs |= KVM_SYNC_FPRS;
3802
3803         if (kvm_is_ucontrol(vcpu->kvm)) {
3804                 rc = __kvm_ucontrol_vcpu_init(vcpu);
3805                 if (rc)
3806                         goto out_free_sie_block;
3807         }
3808
3809         VM_EVENT(vcpu->kvm, 3, "create cpu %d at 0x%pK, sie block at 0x%pK",
3810                  vcpu->vcpu_id, vcpu, vcpu->arch.sie_block);
3811         trace_kvm_s390_create_vcpu(vcpu->vcpu_id, vcpu, vcpu->arch.sie_block);
3812
3813         rc = kvm_s390_vcpu_setup(vcpu);
3814         if (rc)
3815                 goto out_ucontrol_uninit;
3816
3817         kvm_s390_update_topology_change_report(vcpu->kvm, 1);
3818         return 0;
3819
3820 out_ucontrol_uninit:
3821         if (kvm_is_ucontrol(vcpu->kvm))
3822                 gmap_remove(vcpu->arch.gmap);
3823 out_free_sie_block:
3824         free_page((unsigned long)(vcpu->arch.sie_block));
3825         return rc;
3826 }
3827
3828 int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
3829 {
3830         clear_bit(vcpu->vcpu_idx, vcpu->kvm->arch.gisa_int.kicked_mask);
3831         return kvm_s390_vcpu_has_irq(vcpu, 0);
3832 }
3833
3834 bool kvm_arch_vcpu_in_kernel(struct kvm_vcpu *vcpu)
3835 {
3836         return !(vcpu->arch.sie_block->gpsw.mask & PSW_MASK_PSTATE);
3837 }
3838
3839 void kvm_s390_vcpu_block(struct kvm_vcpu *vcpu)
3840 {
3841         atomic_or(PROG_BLOCK_SIE, &vcpu->arch.sie_block->prog20);
3842         exit_sie(vcpu);
3843 }
3844
3845 void kvm_s390_vcpu_unblock(struct kvm_vcpu *vcpu)
3846 {
3847         atomic_andnot(PROG_BLOCK_SIE, &vcpu->arch.sie_block->prog20);
3848 }
3849
3850 static void kvm_s390_vcpu_request(struct kvm_vcpu *vcpu)
3851 {
3852         atomic_or(PROG_REQUEST, &vcpu->arch.sie_block->prog20);
3853         exit_sie(vcpu);
3854 }
3855
3856 bool kvm_s390_vcpu_sie_inhibited(struct kvm_vcpu *vcpu)
3857 {
3858         return atomic_read(&vcpu->arch.sie_block->prog20) &
3859                (PROG_BLOCK_SIE | PROG_REQUEST);
3860 }
3861
3862 static void kvm_s390_vcpu_request_handled(struct kvm_vcpu *vcpu)
3863 {
3864         atomic_andnot(PROG_REQUEST, &vcpu->arch.sie_block->prog20);
3865 }
3866
3867 /*
3868  * Kick a guest cpu out of (v)SIE and wait until (v)SIE is not running.
3869  * If the CPU is not running (e.g. waiting as idle) the function will
3870  * return immediately. */
3871 void exit_sie(struct kvm_vcpu *vcpu)
3872 {
3873         kvm_s390_set_cpuflags(vcpu, CPUSTAT_STOP_INT);
3874         kvm_s390_vsie_kick(vcpu);
3875         while (vcpu->arch.sie_block->prog0c & PROG_IN_SIE)
3876                 cpu_relax();
3877 }
3878
3879 /* Kick a guest cpu out of SIE to process a request synchronously */
3880 void kvm_s390_sync_request(int req, struct kvm_vcpu *vcpu)
3881 {
3882         __kvm_make_request(req, vcpu);
3883         kvm_s390_vcpu_request(vcpu);
3884 }
3885
3886 static void kvm_gmap_notifier(struct gmap *gmap, unsigned long start,
3887                               unsigned long end)
3888 {
3889         struct kvm *kvm = gmap->private;
3890         struct kvm_vcpu *vcpu;
3891         unsigned long prefix;
3892         unsigned long i;
3893
3894         if (gmap_is_shadow(gmap))
3895                 return;
3896         if (start >= 1UL << 31)
3897                 /* We are only interested in prefix pages */
3898                 return;
3899         kvm_for_each_vcpu(i, vcpu, kvm) {
3900                 /* match against both prefix pages */
3901                 prefix = kvm_s390_get_prefix(vcpu);
3902                 if (prefix <= end && start <= prefix + 2*PAGE_SIZE - 1) {
3903                         VCPU_EVENT(vcpu, 2, "gmap notifier for %lx-%lx",
3904                                    start, end);
3905                         kvm_s390_sync_request(KVM_REQ_REFRESH_GUEST_PREFIX, vcpu);
3906                 }
3907         }
3908 }
3909
3910 bool kvm_arch_no_poll(struct kvm_vcpu *vcpu)
3911 {
3912         /* do not poll with more than halt_poll_max_steal percent of steal time */
3913         if (S390_lowcore.avg_steal_timer * 100 / (TICK_USEC << 12) >=
3914             READ_ONCE(halt_poll_max_steal)) {
3915                 vcpu->stat.halt_no_poll_steal++;
3916                 return true;
3917         }
3918         return false;
3919 }
3920
3921 int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu)
3922 {
3923         /* kvm common code refers to this, but never calls it */
3924         BUG();
3925         return 0;
3926 }
3927
3928 static int kvm_arch_vcpu_ioctl_get_one_reg(struct kvm_vcpu *vcpu,
3929                                            struct kvm_one_reg *reg)
3930 {
3931         int r = -EINVAL;
3932
3933         switch (reg->id) {
3934         case KVM_REG_S390_TODPR:
3935                 r = put_user(vcpu->arch.sie_block->todpr,
3936                              (u32 __user *)reg->addr);
3937                 break;
3938         case KVM_REG_S390_EPOCHDIFF:
3939                 r = put_user(vcpu->arch.sie_block->epoch,
3940                              (u64 __user *)reg->addr);
3941                 break;
3942         case KVM_REG_S390_CPU_TIMER:
3943                 r = put_user(kvm_s390_get_cpu_timer(vcpu),
3944                              (u64 __user *)reg->addr);
3945                 break;
3946         case KVM_REG_S390_CLOCK_COMP:
3947                 r = put_user(vcpu->arch.sie_block->ckc,
3948                              (u64 __user *)reg->addr);
3949                 break;
3950         case KVM_REG_S390_PFTOKEN:
3951                 r = put_user(vcpu->arch.pfault_token,
3952                              (u64 __user *)reg->addr);
3953                 break;
3954         case KVM_REG_S390_PFCOMPARE:
3955                 r = put_user(vcpu->arch.pfault_compare,
3956                              (u64 __user *)reg->addr);
3957                 break;
3958         case KVM_REG_S390_PFSELECT:
3959                 r = put_user(vcpu->arch.pfault_select,
3960                              (u64 __user *)reg->addr);
3961                 break;
3962         case KVM_REG_S390_PP:
3963                 r = put_user(vcpu->arch.sie_block->pp,
3964                              (u64 __user *)reg->addr);
3965                 break;
3966         case KVM_REG_S390_GBEA:
3967                 r = put_user(vcpu->arch.sie_block->gbea,
3968                              (u64 __user *)reg->addr);
3969                 break;
3970         default:
3971                 break;
3972         }
3973
3974         return r;
3975 }
3976
3977 static int kvm_arch_vcpu_ioctl_set_one_reg(struct kvm_vcpu *vcpu,
3978                                            struct kvm_one_reg *reg)
3979 {
3980         int r = -EINVAL;
3981         __u64 val;
3982
3983         switch (reg->id) {
3984         case KVM_REG_S390_TODPR:
3985                 r = get_user(vcpu->arch.sie_block->todpr,
3986                              (u32 __user *)reg->addr);
3987                 break;
3988         case KVM_REG_S390_EPOCHDIFF:
3989                 r = get_user(vcpu->arch.sie_block->epoch,
3990                              (u64 __user *)reg->addr);
3991                 break;
3992         case KVM_REG_S390_CPU_TIMER:
3993                 r = get_user(val, (u64 __user *)reg->addr);
3994                 if (!r)
3995                         kvm_s390_set_cpu_timer(vcpu, val);
3996                 break;
3997         case KVM_REG_S390_CLOCK_COMP:
3998                 r = get_user(vcpu->arch.sie_block->ckc,
3999                              (u64 __user *)reg->addr);
4000                 break;
4001         case KVM_REG_S390_PFTOKEN:
4002                 r = get_user(vcpu->arch.pfault_token,
4003                              (u64 __user *)reg->addr);
4004                 if (vcpu->arch.pfault_token == KVM_S390_PFAULT_TOKEN_INVALID)
4005                         kvm_clear_async_pf_completion_queue(vcpu);
4006                 break;
4007         case KVM_REG_S390_PFCOMPARE:
4008                 r = get_user(vcpu->arch.pfault_compare,
4009                              (u64 __user *)reg->addr);
4010                 break;
4011         case KVM_REG_S390_PFSELECT:
4012                 r = get_user(vcpu->arch.pfault_select,
4013                              (u64 __user *)reg->addr);
4014                 break;
4015         case KVM_REG_S390_PP:
4016                 r = get_user(vcpu->arch.sie_block->pp,
4017                              (u64 __user *)reg->addr);
4018                 break;
4019         case KVM_REG_S390_GBEA:
4020                 r = get_user(vcpu->arch.sie_block->gbea,
4021                              (u64 __user *)reg->addr);
4022                 break;
4023         default:
4024                 break;
4025         }
4026
4027         return r;
4028 }
4029
4030 static void kvm_arch_vcpu_ioctl_normal_reset(struct kvm_vcpu *vcpu)
4031 {
4032         vcpu->arch.sie_block->gpsw.mask &= ~PSW_MASK_RI;
4033         vcpu->arch.pfault_token = KVM_S390_PFAULT_TOKEN_INVALID;
4034         memset(vcpu->run->s.regs.riccb, 0, sizeof(vcpu->run->s.regs.riccb));
4035
4036         kvm_clear_async_pf_completion_queue(vcpu);
4037         if (!kvm_s390_user_cpu_state_ctrl(vcpu->kvm))
4038                 kvm_s390_vcpu_stop(vcpu);
4039         kvm_s390_clear_local_irqs(vcpu);
4040 }
4041
4042 static void kvm_arch_vcpu_ioctl_initial_reset(struct kvm_vcpu *vcpu)
4043 {
4044         /* Initial reset is a superset of the normal reset */
4045         kvm_arch_vcpu_ioctl_normal_reset(vcpu);
4046
4047         /*
4048          * This equals initial cpu reset in pop, but we don't switch to ESA.
4049          * We do not only reset the internal data, but also ...
4050          */
4051         vcpu->arch.sie_block->gpsw.mask = 0;
4052         vcpu->arch.sie_block->gpsw.addr = 0;
4053         kvm_s390_set_prefix(vcpu, 0);
4054         kvm_s390_set_cpu_timer(vcpu, 0);
4055         vcpu->arch.sie_block->ckc = 0;
4056         memset(vcpu->arch.sie_block->gcr, 0, sizeof(vcpu->arch.sie_block->gcr));
4057         vcpu->arch.sie_block->gcr[0] = CR0_INITIAL_MASK;
4058         vcpu->arch.sie_block->gcr[14] = CR14_INITIAL_MASK;
4059
4060         /* ... the data in sync regs */
4061         memset(vcpu->run->s.regs.crs, 0, sizeof(vcpu->run->s.regs.crs));
4062         vcpu->run->s.regs.ckc = 0;
4063         vcpu->run->s.regs.crs[0] = CR0_INITIAL_MASK;
4064         vcpu->run->s.regs.crs[14] = CR14_INITIAL_MASK;
4065         vcpu->run->psw_addr = 0;
4066         vcpu->run->psw_mask = 0;
4067         vcpu->run->s.regs.todpr = 0;
4068         vcpu->run->s.regs.cputm = 0;
4069         vcpu->run->s.regs.ckc = 0;
4070         vcpu->run->s.regs.pp = 0;
4071         vcpu->run->s.regs.gbea = 1;
4072         vcpu->run->s.regs.fpc = 0;
4073         /*
4074          * Do not reset these registers in the protected case, as some of
4075          * them are overlayed and they are not accessible in this case
4076          * anyway.
4077          */
4078         if (!kvm_s390_pv_cpu_is_protected(vcpu)) {
4079                 vcpu->arch.sie_block->gbea = 1;
4080                 vcpu->arch.sie_block->pp = 0;
4081                 vcpu->arch.sie_block->fpf &= ~FPF_BPBC;
4082                 vcpu->arch.sie_block->todpr = 0;
4083         }
4084 }
4085
4086 static void kvm_arch_vcpu_ioctl_clear_reset(struct kvm_vcpu *vcpu)
4087 {
4088         struct kvm_sync_regs *regs = &vcpu->run->s.regs;
4089
4090         /* Clear reset is a superset of the initial reset */
4091         kvm_arch_vcpu_ioctl_initial_reset(vcpu);
4092
4093         memset(&regs->gprs, 0, sizeof(regs->gprs));
4094         memset(&regs->vrs, 0, sizeof(regs->vrs));
4095         memset(&regs->acrs, 0, sizeof(regs->acrs));
4096         memset(&regs->gscb, 0, sizeof(regs->gscb));
4097
4098         regs->etoken = 0;
4099         regs->etoken_extension = 0;
4100 }
4101
4102 int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
4103 {
4104         vcpu_load(vcpu);
4105         memcpy(&vcpu->run->s.regs.gprs, &regs->gprs, sizeof(regs->gprs));
4106         vcpu_put(vcpu);
4107         return 0;
4108 }
4109
4110 int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
4111 {
4112         vcpu_load(vcpu);
4113         memcpy(&regs->gprs, &vcpu->run->s.regs.gprs, sizeof(regs->gprs));
4114         vcpu_put(vcpu);
4115         return 0;
4116 }
4117
4118 int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
4119                                   struct kvm_sregs *sregs)
4120 {
4121         vcpu_load(vcpu);
4122
4123         memcpy(&vcpu->run->s.regs.acrs, &sregs->acrs, sizeof(sregs->acrs));
4124         memcpy(&vcpu->arch.sie_block->gcr, &sregs->crs, sizeof(sregs->crs));
4125
4126         vcpu_put(vcpu);
4127         return 0;
4128 }
4129
4130 int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
4131                                   struct kvm_sregs *sregs)
4132 {
4133         vcpu_load(vcpu);
4134
4135         memcpy(&sregs->acrs, &vcpu->run->s.regs.acrs, sizeof(sregs->acrs));
4136         memcpy(&sregs->crs, &vcpu->arch.sie_block->gcr, sizeof(sregs->crs));
4137
4138         vcpu_put(vcpu);
4139         return 0;
4140 }
4141
4142 int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
4143 {
4144         int ret = 0;
4145
4146         vcpu_load(vcpu);
4147
4148         vcpu->run->s.regs.fpc = fpu->fpc;
4149         if (MACHINE_HAS_VX)
4150                 convert_fp_to_vx((__vector128 *) vcpu->run->s.regs.vrs,
4151                                  (freg_t *) fpu->fprs);
4152         else
4153                 memcpy(vcpu->run->s.regs.fprs, &fpu->fprs, sizeof(fpu->fprs));
4154
4155         vcpu_put(vcpu);
4156         return ret;
4157 }
4158
4159 int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
4160 {
4161         vcpu_load(vcpu);
4162
4163         /* make sure we have the latest values */
4164         save_fpu_regs();
4165         if (MACHINE_HAS_VX)
4166                 convert_vx_to_fp((freg_t *) fpu->fprs,
4167                                  (__vector128 *) vcpu->run->s.regs.vrs);
4168         else
4169                 memcpy(fpu->fprs, vcpu->run->s.regs.fprs, sizeof(fpu->fprs));
4170         fpu->fpc = vcpu->run->s.regs.fpc;
4171
4172         vcpu_put(vcpu);
4173         return 0;
4174 }
4175
4176 static int kvm_arch_vcpu_ioctl_set_initial_psw(struct kvm_vcpu *vcpu, psw_t psw)
4177 {
4178         int rc = 0;
4179
4180         if (!is_vcpu_stopped(vcpu))
4181                 rc = -EBUSY;
4182         else {
4183                 vcpu->run->psw_mask = psw.mask;
4184                 vcpu->run->psw_addr = psw.addr;
4185         }
4186         return rc;
4187 }
4188
4189 int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
4190                                   struct kvm_translation *tr)
4191 {
4192         return -EINVAL; /* not implemented yet */
4193 }
4194
4195 #define VALID_GUESTDBG_FLAGS (KVM_GUESTDBG_SINGLESTEP | \
4196                               KVM_GUESTDBG_USE_HW_BP | \
4197                               KVM_GUESTDBG_ENABLE)
4198
4199 int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu,
4200                                         struct kvm_guest_debug *dbg)
4201 {
4202         int rc = 0;
4203
4204         vcpu_load(vcpu);
4205
4206         vcpu->guest_debug = 0;
4207         kvm_s390_clear_bp_data(vcpu);
4208
4209         if (dbg->control & ~VALID_GUESTDBG_FLAGS) {
4210                 rc = -EINVAL;
4211                 goto out;
4212         }
4213         if (!sclp.has_gpere) {
4214                 rc = -EINVAL;
4215                 goto out;
4216         }
4217
4218         if (dbg->control & KVM_GUESTDBG_ENABLE) {
4219                 vcpu->guest_debug = dbg->control;
4220                 /* enforce guest PER */
4221                 kvm_s390_set_cpuflags(vcpu, CPUSTAT_P);
4222
4223                 if (dbg->control & KVM_GUESTDBG_USE_HW_BP)
4224                         rc = kvm_s390_import_bp_data(vcpu, dbg);
4225         } else {
4226                 kvm_s390_clear_cpuflags(vcpu, CPUSTAT_P);
4227                 vcpu->arch.guestdbg.last_bp = 0;
4228         }
4229
4230         if (rc) {
4231                 vcpu->guest_debug = 0;
4232                 kvm_s390_clear_bp_data(vcpu);
4233                 kvm_s390_clear_cpuflags(vcpu, CPUSTAT_P);
4234         }
4235
4236 out:
4237         vcpu_put(vcpu);
4238         return rc;
4239 }
4240
4241 int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
4242                                     struct kvm_mp_state *mp_state)
4243 {
4244         int ret;
4245
4246         vcpu_load(vcpu);
4247
4248         /* CHECK_STOP and LOAD are not supported yet */
4249         ret = is_vcpu_stopped(vcpu) ? KVM_MP_STATE_STOPPED :
4250                                       KVM_MP_STATE_OPERATING;
4251
4252         vcpu_put(vcpu);
4253         return ret;
4254 }
4255
4256 int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
4257                                     struct kvm_mp_state *mp_state)
4258 {
4259         int rc = 0;
4260
4261         vcpu_load(vcpu);
4262
4263         /* user space knows about this interface - let it control the state */
4264         kvm_s390_set_user_cpu_state_ctrl(vcpu->kvm);
4265
4266         switch (mp_state->mp_state) {
4267         case KVM_MP_STATE_STOPPED:
4268                 rc = kvm_s390_vcpu_stop(vcpu);
4269                 break;
4270         case KVM_MP_STATE_OPERATING:
4271                 rc = kvm_s390_vcpu_start(vcpu);
4272                 break;
4273         case KVM_MP_STATE_LOAD:
4274                 if (!kvm_s390_pv_cpu_is_protected(vcpu)) {
4275                         rc = -ENXIO;
4276                         break;
4277                 }
4278                 rc = kvm_s390_pv_set_cpu_state(vcpu, PV_CPU_STATE_OPR_LOAD);
4279                 break;
4280         case KVM_MP_STATE_CHECK_STOP:
4281                 fallthrough;    /* CHECK_STOP and LOAD are not supported yet */
4282         default:
4283                 rc = -ENXIO;
4284         }
4285
4286         vcpu_put(vcpu);
4287         return rc;
4288 }
4289
4290 static bool ibs_enabled(struct kvm_vcpu *vcpu)
4291 {
4292         return kvm_s390_test_cpuflags(vcpu, CPUSTAT_IBS);
4293 }
4294
4295 static int kvm_s390_handle_requests(struct kvm_vcpu *vcpu)
4296 {
4297 retry:
4298         kvm_s390_vcpu_request_handled(vcpu);
4299         if (!kvm_request_pending(vcpu))
4300                 return 0;
4301         /*
4302          * If the guest prefix changed, re-arm the ipte notifier for the
4303          * guest prefix page. gmap_mprotect_notify will wait on the ptl lock.
4304          * This ensures that the ipte instruction for this request has
4305          * already finished. We might race against a second unmapper that
4306          * wants to set the blocking bit. Lets just retry the request loop.
4307          */
4308         if (kvm_check_request(KVM_REQ_REFRESH_GUEST_PREFIX, vcpu)) {
4309                 int rc;
4310                 rc = gmap_mprotect_notify(vcpu->arch.gmap,
4311                                           kvm_s390_get_prefix(vcpu),
4312                                           PAGE_SIZE * 2, PROT_WRITE);
4313                 if (rc) {
4314                         kvm_make_request(KVM_REQ_REFRESH_GUEST_PREFIX, vcpu);
4315                         return rc;
4316                 }
4317                 goto retry;
4318         }
4319
4320         if (kvm_check_request(KVM_REQ_TLB_FLUSH, vcpu)) {
4321                 vcpu->arch.sie_block->ihcpu = 0xffff;
4322                 goto retry;
4323         }
4324
4325         if (kvm_check_request(KVM_REQ_ENABLE_IBS, vcpu)) {
4326                 if (!ibs_enabled(vcpu)) {
4327                         trace_kvm_s390_enable_disable_ibs(vcpu->vcpu_id, 1);
4328                         kvm_s390_set_cpuflags(vcpu, CPUSTAT_IBS);
4329                 }
4330                 goto retry;
4331         }
4332
4333         if (kvm_check_request(KVM_REQ_DISABLE_IBS, vcpu)) {
4334                 if (ibs_enabled(vcpu)) {
4335                         trace_kvm_s390_enable_disable_ibs(vcpu->vcpu_id, 0);
4336                         kvm_s390_clear_cpuflags(vcpu, CPUSTAT_IBS);
4337                 }
4338                 goto retry;
4339         }
4340
4341         if (kvm_check_request(KVM_REQ_ICPT_OPEREXC, vcpu)) {
4342                 vcpu->arch.sie_block->ictl |= ICTL_OPEREXC;
4343                 goto retry;
4344         }
4345
4346         if (kvm_check_request(KVM_REQ_START_MIGRATION, vcpu)) {
4347                 /*
4348                  * Disable CMM virtualization; we will emulate the ESSA
4349                  * instruction manually, in order to provide additional
4350                  * functionalities needed for live migration.
4351                  */
4352                 vcpu->arch.sie_block->ecb2 &= ~ECB2_CMMA;
4353                 goto retry;
4354         }
4355
4356         if (kvm_check_request(KVM_REQ_STOP_MIGRATION, vcpu)) {
4357                 /*
4358                  * Re-enable CMM virtualization if CMMA is available and
4359                  * CMM has been used.
4360                  */
4361                 if ((vcpu->kvm->arch.use_cmma) &&
4362                     (vcpu->kvm->mm->context.uses_cmm))
4363                         vcpu->arch.sie_block->ecb2 |= ECB2_CMMA;
4364                 goto retry;
4365         }
4366
4367         /* we left the vsie handler, nothing to do, just clear the request */
4368         kvm_clear_request(KVM_REQ_VSIE_RESTART, vcpu);
4369
4370         return 0;
4371 }
4372
4373 static void __kvm_s390_set_tod_clock(struct kvm *kvm, const struct kvm_s390_vm_tod_clock *gtod)
4374 {
4375         struct kvm_vcpu *vcpu;
4376         union tod_clock clk;
4377         unsigned long i;
4378
4379         preempt_disable();
4380
4381         store_tod_clock_ext(&clk);
4382
4383         kvm->arch.epoch = gtod->tod - clk.tod;
4384         kvm->arch.epdx = 0;
4385         if (test_kvm_facility(kvm, 139)) {
4386                 kvm->arch.epdx = gtod->epoch_idx - clk.ei;
4387                 if (kvm->arch.epoch > gtod->tod)
4388                         kvm->arch.epdx -= 1;
4389         }
4390
4391         kvm_s390_vcpu_block_all(kvm);
4392         kvm_for_each_vcpu(i, vcpu, kvm) {
4393                 vcpu->arch.sie_block->epoch = kvm->arch.epoch;
4394                 vcpu->arch.sie_block->epdx  = kvm->arch.epdx;
4395         }
4396
4397         kvm_s390_vcpu_unblock_all(kvm);
4398         preempt_enable();
4399 }
4400
4401 int kvm_s390_try_set_tod_clock(struct kvm *kvm, const struct kvm_s390_vm_tod_clock *gtod)
4402 {
4403         if (!mutex_trylock(&kvm->lock))
4404                 return 0;
4405         __kvm_s390_set_tod_clock(kvm, gtod);
4406         mutex_unlock(&kvm->lock);
4407         return 1;
4408 }
4409
4410 /**
4411  * kvm_arch_fault_in_page - fault-in guest page if necessary
4412  * @vcpu: The corresponding virtual cpu
4413  * @gpa: Guest physical address
4414  * @writable: Whether the page should be writable or not
4415  *
4416  * Make sure that a guest page has been faulted-in on the host.
4417  *
4418  * Return: Zero on success, negative error code otherwise.
4419  */
4420 long kvm_arch_fault_in_page(struct kvm_vcpu *vcpu, gpa_t gpa, int writable)
4421 {
4422         return gmap_fault(vcpu->arch.gmap, gpa,
4423                           writable ? FAULT_FLAG_WRITE : 0);
4424 }
4425
4426 static void __kvm_inject_pfault_token(struct kvm_vcpu *vcpu, bool start_token,
4427                                       unsigned long token)
4428 {
4429         struct kvm_s390_interrupt inti;
4430         struct kvm_s390_irq irq;
4431
4432         if (start_token) {
4433                 irq.u.ext.ext_params2 = token;
4434                 irq.type = KVM_S390_INT_PFAULT_INIT;
4435                 WARN_ON_ONCE(kvm_s390_inject_vcpu(vcpu, &irq));
4436         } else {
4437                 inti.type = KVM_S390_INT_PFAULT_DONE;
4438                 inti.parm64 = token;
4439                 WARN_ON_ONCE(kvm_s390_inject_vm(vcpu->kvm, &inti));
4440         }
4441 }
4442
4443 bool kvm_arch_async_page_not_present(struct kvm_vcpu *vcpu,
4444                                      struct kvm_async_pf *work)
4445 {
4446         trace_kvm_s390_pfault_init(vcpu, work->arch.pfault_token);
4447         __kvm_inject_pfault_token(vcpu, true, work->arch.pfault_token);
4448
4449         return true;
4450 }
4451
4452 void kvm_arch_async_page_present(struct kvm_vcpu *vcpu,
4453                                  struct kvm_async_pf *work)
4454 {
4455         trace_kvm_s390_pfault_done(vcpu, work->arch.pfault_token);
4456         __kvm_inject_pfault_token(vcpu, false, work->arch.pfault_token);
4457 }
4458
4459 void kvm_arch_async_page_ready(struct kvm_vcpu *vcpu,
4460                                struct kvm_async_pf *work)
4461 {
4462         /* s390 will always inject the page directly */
4463 }
4464
4465 bool kvm_arch_can_dequeue_async_page_present(struct kvm_vcpu *vcpu)
4466 {
4467         /*
4468          * s390 will always inject the page directly,
4469          * but we still want check_async_completion to cleanup
4470          */
4471         return true;
4472 }
4473
4474 static bool kvm_arch_setup_async_pf(struct kvm_vcpu *vcpu)
4475 {
4476         hva_t hva;
4477         struct kvm_arch_async_pf arch;
4478
4479         if (vcpu->arch.pfault_token == KVM_S390_PFAULT_TOKEN_INVALID)
4480                 return false;
4481         if ((vcpu->arch.sie_block->gpsw.mask & vcpu->arch.pfault_select) !=
4482             vcpu->arch.pfault_compare)
4483                 return false;
4484         if (psw_extint_disabled(vcpu))
4485                 return false;
4486         if (kvm_s390_vcpu_has_irq(vcpu, 0))
4487                 return false;
4488         if (!(vcpu->arch.sie_block->gcr[0] & CR0_SERVICE_SIGNAL_SUBMASK))
4489                 return false;
4490         if (!vcpu->arch.gmap->pfault_enabled)
4491                 return false;
4492
4493         hva = gfn_to_hva(vcpu->kvm, gpa_to_gfn(current->thread.gmap_addr));
4494         hva += current->thread.gmap_addr & ~PAGE_MASK;
4495         if (read_guest_real(vcpu, vcpu->arch.pfault_token, &arch.pfault_token, 8))
4496                 return false;
4497
4498         return kvm_setup_async_pf(vcpu, current->thread.gmap_addr, hva, &arch);
4499 }
4500
4501 static int vcpu_pre_run(struct kvm_vcpu *vcpu)
4502 {
4503         int rc, cpuflags;
4504
4505         /*
4506          * On s390 notifications for arriving pages will be delivered directly
4507          * to the guest but the house keeping for completed pfaults is
4508          * handled outside the worker.
4509          */
4510         kvm_check_async_pf_completion(vcpu);
4511
4512         vcpu->arch.sie_block->gg14 = vcpu->run->s.regs.gprs[14];
4513         vcpu->arch.sie_block->gg15 = vcpu->run->s.regs.gprs[15];
4514
4515         if (need_resched())
4516                 schedule();
4517
4518         if (!kvm_is_ucontrol(vcpu->kvm)) {
4519                 rc = kvm_s390_deliver_pending_interrupts(vcpu);
4520                 if (rc)
4521                         return rc;
4522         }
4523
4524         rc = kvm_s390_handle_requests(vcpu);
4525         if (rc)
4526                 return rc;
4527
4528         if (guestdbg_enabled(vcpu)) {
4529                 kvm_s390_backup_guest_per_regs(vcpu);
4530                 kvm_s390_patch_guest_per_regs(vcpu);
4531         }
4532
4533         clear_bit(vcpu->vcpu_idx, vcpu->kvm->arch.gisa_int.kicked_mask);
4534
4535         vcpu->arch.sie_block->icptcode = 0;
4536         cpuflags = atomic_read(&vcpu->arch.sie_block->cpuflags);
4537         VCPU_EVENT(vcpu, 6, "entering sie flags %x", cpuflags);
4538         trace_kvm_s390_sie_enter(vcpu, cpuflags);
4539
4540         return 0;
4541 }
4542
4543 static int vcpu_post_run_fault_in_sie(struct kvm_vcpu *vcpu)
4544 {
4545         struct kvm_s390_pgm_info pgm_info = {
4546                 .code = PGM_ADDRESSING,
4547         };
4548         u8 opcode, ilen;
4549         int rc;
4550
4551         VCPU_EVENT(vcpu, 3, "%s", "fault in sie instruction");
4552         trace_kvm_s390_sie_fault(vcpu);
4553
4554         /*
4555          * We want to inject an addressing exception, which is defined as a
4556          * suppressing or terminating exception. However, since we came here
4557          * by a DAT access exception, the PSW still points to the faulting
4558          * instruction since DAT exceptions are nullifying. So we've got
4559          * to look up the current opcode to get the length of the instruction
4560          * to be able to forward the PSW.
4561          */
4562         rc = read_guest_instr(vcpu, vcpu->arch.sie_block->gpsw.addr, &opcode, 1);
4563         ilen = insn_length(opcode);
4564         if (rc < 0) {
4565                 return rc;
4566         } else if (rc) {
4567                 /* Instruction-Fetching Exceptions - we can't detect the ilen.
4568                  * Forward by arbitrary ilc, injection will take care of
4569                  * nullification if necessary.
4570                  */
4571                 pgm_info = vcpu->arch.pgm;
4572                 ilen = 4;
4573         }
4574         pgm_info.flags = ilen | KVM_S390_PGM_FLAGS_ILC_VALID;
4575         kvm_s390_forward_psw(vcpu, ilen);
4576         return kvm_s390_inject_prog_irq(vcpu, &pgm_info);
4577 }
4578
4579 static int vcpu_post_run(struct kvm_vcpu *vcpu, int exit_reason)
4580 {
4581         struct mcck_volatile_info *mcck_info;
4582         struct sie_page *sie_page;
4583
4584         VCPU_EVENT(vcpu, 6, "exit sie icptcode %d",
4585                    vcpu->arch.sie_block->icptcode);
4586         trace_kvm_s390_sie_exit(vcpu, vcpu->arch.sie_block->icptcode);
4587
4588         if (guestdbg_enabled(vcpu))
4589                 kvm_s390_restore_guest_per_regs(vcpu);
4590
4591         vcpu->run->s.regs.gprs[14] = vcpu->arch.sie_block->gg14;
4592         vcpu->run->s.regs.gprs[15] = vcpu->arch.sie_block->gg15;
4593
4594         if (exit_reason == -EINTR) {
4595                 VCPU_EVENT(vcpu, 3, "%s", "machine check");
4596                 sie_page = container_of(vcpu->arch.sie_block,
4597                                         struct sie_page, sie_block);
4598                 mcck_info = &sie_page->mcck_info;
4599                 kvm_s390_reinject_machine_check(vcpu, mcck_info);
4600                 return 0;
4601         }
4602
4603         if (vcpu->arch.sie_block->icptcode > 0) {
4604                 int rc = kvm_handle_sie_intercept(vcpu);
4605
4606                 if (rc != -EOPNOTSUPP)
4607                         return rc;
4608                 vcpu->run->exit_reason = KVM_EXIT_S390_SIEIC;
4609                 vcpu->run->s390_sieic.icptcode = vcpu->arch.sie_block->icptcode;
4610                 vcpu->run->s390_sieic.ipa = vcpu->arch.sie_block->ipa;
4611                 vcpu->run->s390_sieic.ipb = vcpu->arch.sie_block->ipb;
4612                 return -EREMOTE;
4613         } else if (exit_reason != -EFAULT) {
4614                 vcpu->stat.exit_null++;
4615                 return 0;
4616         } else if (kvm_is_ucontrol(vcpu->kvm)) {
4617                 vcpu->run->exit_reason = KVM_EXIT_S390_UCONTROL;
4618                 vcpu->run->s390_ucontrol.trans_exc_code =
4619                                                 current->thread.gmap_addr;
4620                 vcpu->run->s390_ucontrol.pgm_code = 0x10;
4621                 return -EREMOTE;
4622         } else if (current->thread.gmap_pfault) {
4623                 trace_kvm_s390_major_guest_pfault(vcpu);
4624                 current->thread.gmap_pfault = 0;
4625                 if (kvm_arch_setup_async_pf(vcpu))
4626                         return 0;
4627                 vcpu->stat.pfault_sync++;
4628                 return kvm_arch_fault_in_page(vcpu, current->thread.gmap_addr, 1);
4629         }
4630         return vcpu_post_run_fault_in_sie(vcpu);
4631 }
4632
4633 #define PSW_INT_MASK (PSW_MASK_EXT | PSW_MASK_IO | PSW_MASK_MCHECK)
4634 static int __vcpu_run(struct kvm_vcpu *vcpu)
4635 {
4636         int rc, exit_reason;
4637         struct sie_page *sie_page = (struct sie_page *)vcpu->arch.sie_block;
4638
4639         /*
4640          * We try to hold kvm->srcu during most of vcpu_run (except when run-
4641          * ning the guest), so that memslots (and other stuff) are protected
4642          */
4643         kvm_vcpu_srcu_read_lock(vcpu);
4644
4645         do {
4646                 rc = vcpu_pre_run(vcpu);
4647                 if (rc)
4648                         break;
4649
4650                 kvm_vcpu_srcu_read_unlock(vcpu);
4651                 /*
4652                  * As PF_VCPU will be used in fault handler, between
4653                  * guest_enter and guest_exit should be no uaccess.
4654                  */
4655                 local_irq_disable();
4656                 guest_enter_irqoff();
4657                 __disable_cpu_timer_accounting(vcpu);
4658                 local_irq_enable();
4659                 if (kvm_s390_pv_cpu_is_protected(vcpu)) {
4660                         memcpy(sie_page->pv_grregs,
4661                                vcpu->run->s.regs.gprs,
4662                                sizeof(sie_page->pv_grregs));
4663                 }
4664                 if (test_cpu_flag(CIF_FPU))
4665                         load_fpu_regs();
4666                 exit_reason = sie64a(vcpu->arch.sie_block,
4667                                      vcpu->run->s.regs.gprs);
4668                 if (kvm_s390_pv_cpu_is_protected(vcpu)) {
4669                         memcpy(vcpu->run->s.regs.gprs,
4670                                sie_page->pv_grregs,
4671                                sizeof(sie_page->pv_grregs));
4672                         /*
4673                          * We're not allowed to inject interrupts on intercepts
4674                          * that leave the guest state in an "in-between" state
4675                          * where the next SIE entry will do a continuation.
4676                          * Fence interrupts in our "internal" PSW.
4677                          */
4678                         if (vcpu->arch.sie_block->icptcode == ICPT_PV_INSTR ||
4679                             vcpu->arch.sie_block->icptcode == ICPT_PV_PREF) {
4680                                 vcpu->arch.sie_block->gpsw.mask &= ~PSW_INT_MASK;
4681                         }
4682                 }
4683                 local_irq_disable();
4684                 __enable_cpu_timer_accounting(vcpu);
4685                 guest_exit_irqoff();
4686                 local_irq_enable();
4687                 kvm_vcpu_srcu_read_lock(vcpu);
4688
4689                 rc = vcpu_post_run(vcpu, exit_reason);
4690         } while (!signal_pending(current) && !guestdbg_exit_pending(vcpu) && !rc);
4691
4692         kvm_vcpu_srcu_read_unlock(vcpu);
4693         return rc;
4694 }
4695
4696 static void sync_regs_fmt2(struct kvm_vcpu *vcpu)
4697 {
4698         struct kvm_run *kvm_run = vcpu->run;
4699         struct runtime_instr_cb *riccb;
4700         struct gs_cb *gscb;
4701
4702         riccb = (struct runtime_instr_cb *) &kvm_run->s.regs.riccb;
4703         gscb = (struct gs_cb *) &kvm_run->s.regs.gscb;
4704         vcpu->arch.sie_block->gpsw.mask = kvm_run->psw_mask;
4705         vcpu->arch.sie_block->gpsw.addr = kvm_run->psw_addr;
4706         if (kvm_run->kvm_dirty_regs & KVM_SYNC_ARCH0) {
4707                 vcpu->arch.sie_block->todpr = kvm_run->s.regs.todpr;
4708                 vcpu->arch.sie_block->pp = kvm_run->s.regs.pp;
4709                 vcpu->arch.sie_block->gbea = kvm_run->s.regs.gbea;
4710         }
4711         if (kvm_run->kvm_dirty_regs & KVM_SYNC_PFAULT) {
4712                 vcpu->arch.pfault_token = kvm_run->s.regs.pft;
4713                 vcpu->arch.pfault_select = kvm_run->s.regs.pfs;
4714                 vcpu->arch.pfault_compare = kvm_run->s.regs.pfc;
4715                 if (vcpu->arch.pfault_token == KVM_S390_PFAULT_TOKEN_INVALID)
4716                         kvm_clear_async_pf_completion_queue(vcpu);
4717         }
4718         if (kvm_run->kvm_dirty_regs & KVM_SYNC_DIAG318) {
4719                 vcpu->arch.diag318_info.val = kvm_run->s.regs.diag318;
4720                 vcpu->arch.sie_block->cpnc = vcpu->arch.diag318_info.cpnc;
4721                 VCPU_EVENT(vcpu, 3, "setting cpnc to %d", vcpu->arch.diag318_info.cpnc);
4722         }
4723         /*
4724          * If userspace sets the riccb (e.g. after migration) to a valid state,
4725          * we should enable RI here instead of doing the lazy enablement.
4726          */
4727         if ((kvm_run->kvm_dirty_regs & KVM_SYNC_RICCB) &&
4728             test_kvm_facility(vcpu->kvm, 64) &&
4729             riccb->v &&
4730             !(vcpu->arch.sie_block->ecb3 & ECB3_RI)) {
4731                 VCPU_EVENT(vcpu, 3, "%s", "ENABLE: RI (sync_regs)");
4732                 vcpu->arch.sie_block->ecb3 |= ECB3_RI;
4733         }
4734         /*
4735          * If userspace sets the gscb (e.g. after migration) to non-zero,
4736          * we should enable GS here instead of doing the lazy enablement.
4737          */
4738         if ((kvm_run->kvm_dirty_regs & KVM_SYNC_GSCB) &&
4739             test_kvm_facility(vcpu->kvm, 133) &&
4740             gscb->gssm &&
4741             !vcpu->arch.gs_enabled) {
4742                 VCPU_EVENT(vcpu, 3, "%s", "ENABLE: GS (sync_regs)");
4743                 vcpu->arch.sie_block->ecb |= ECB_GS;
4744                 vcpu->arch.sie_block->ecd |= ECD_HOSTREGMGMT;
4745                 vcpu->arch.gs_enabled = 1;
4746         }
4747         if ((kvm_run->kvm_dirty_regs & KVM_SYNC_BPBC) &&
4748             test_kvm_facility(vcpu->kvm, 82)) {
4749                 vcpu->arch.sie_block->fpf &= ~FPF_BPBC;
4750                 vcpu->arch.sie_block->fpf |= kvm_run->s.regs.bpbc ? FPF_BPBC : 0;
4751         }
4752         if (MACHINE_HAS_GS) {
4753                 preempt_disable();
4754                 __ctl_set_bit(2, 4);
4755                 if (current->thread.gs_cb) {
4756                         vcpu->arch.host_gscb = current->thread.gs_cb;
4757                         save_gs_cb(vcpu->arch.host_gscb);
4758                 }
4759                 if (vcpu->arch.gs_enabled) {
4760                         current->thread.gs_cb = (struct gs_cb *)
4761                                                 &vcpu->run->s.regs.gscb;
4762                         restore_gs_cb(current->thread.gs_cb);
4763                 }
4764                 preempt_enable();
4765         }
4766         /* SIE will load etoken directly from SDNX and therefore kvm_run */
4767 }
4768
4769 static void sync_regs(struct kvm_vcpu *vcpu)
4770 {
4771         struct kvm_run *kvm_run = vcpu->run;
4772
4773         if (kvm_run->kvm_dirty_regs & KVM_SYNC_PREFIX)
4774                 kvm_s390_set_prefix(vcpu, kvm_run->s.regs.prefix);
4775         if (kvm_run->kvm_dirty_regs & KVM_SYNC_CRS) {
4776                 memcpy(&vcpu->arch.sie_block->gcr, &kvm_run->s.regs.crs, 128);
4777                 /* some control register changes require a tlb flush */
4778                 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
4779         }
4780         if (kvm_run->kvm_dirty_regs & KVM_SYNC_ARCH0) {
4781                 kvm_s390_set_cpu_timer(vcpu, kvm_run->s.regs.cputm);
4782                 vcpu->arch.sie_block->ckc = kvm_run->s.regs.ckc;
4783         }
4784         save_access_regs(vcpu->arch.host_acrs);
4785         restore_access_regs(vcpu->run->s.regs.acrs);
4786         /* save host (userspace) fprs/vrs */
4787         save_fpu_regs();
4788         vcpu->arch.host_fpregs.fpc = current->thread.fpu.fpc;
4789         vcpu->arch.host_fpregs.regs = current->thread.fpu.regs;
4790         if (MACHINE_HAS_VX)
4791                 current->thread.fpu.regs = vcpu->run->s.regs.vrs;
4792         else
4793                 current->thread.fpu.regs = vcpu->run->s.regs.fprs;
4794         current->thread.fpu.fpc = vcpu->run->s.regs.fpc;
4795         if (test_fp_ctl(current->thread.fpu.fpc))
4796                 /* User space provided an invalid FPC, let's clear it */
4797                 current->thread.fpu.fpc = 0;
4798
4799         /* Sync fmt2 only data */
4800         if (likely(!kvm_s390_pv_cpu_is_protected(vcpu))) {
4801                 sync_regs_fmt2(vcpu);
4802         } else {
4803                 /*
4804                  * In several places we have to modify our internal view to
4805                  * not do things that are disallowed by the ultravisor. For
4806                  * example we must not inject interrupts after specific exits
4807                  * (e.g. 112 prefix page not secure). We do this by turning
4808                  * off the machine check, external and I/O interrupt bits
4809                  * of our PSW copy. To avoid getting validity intercepts, we
4810                  * do only accept the condition code from userspace.
4811                  */
4812                 vcpu->arch.sie_block->gpsw.mask &= ~PSW_MASK_CC;
4813                 vcpu->arch.sie_block->gpsw.mask |= kvm_run->psw_mask &
4814                                                    PSW_MASK_CC;
4815         }
4816
4817         kvm_run->kvm_dirty_regs = 0;
4818 }
4819
4820 static void store_regs_fmt2(struct kvm_vcpu *vcpu)
4821 {
4822         struct kvm_run *kvm_run = vcpu->run;
4823
4824         kvm_run->s.regs.todpr = vcpu->arch.sie_block->todpr;
4825         kvm_run->s.regs.pp = vcpu->arch.sie_block->pp;
4826         kvm_run->s.regs.gbea = vcpu->arch.sie_block->gbea;
4827         kvm_run->s.regs.bpbc = (vcpu->arch.sie_block->fpf & FPF_BPBC) == FPF_BPBC;
4828         kvm_run->s.regs.diag318 = vcpu->arch.diag318_info.val;
4829         if (MACHINE_HAS_GS) {
4830                 preempt_disable();
4831                 __ctl_set_bit(2, 4);
4832                 if (vcpu->arch.gs_enabled)
4833                         save_gs_cb(current->thread.gs_cb);
4834                 current->thread.gs_cb = vcpu->arch.host_gscb;
4835                 restore_gs_cb(vcpu->arch.host_gscb);
4836                 if (!vcpu->arch.host_gscb)
4837                         __ctl_clear_bit(2, 4);
4838                 vcpu->arch.host_gscb = NULL;
4839                 preempt_enable();
4840         }
4841         /* SIE will save etoken directly into SDNX and therefore kvm_run */
4842 }
4843
4844 static void store_regs(struct kvm_vcpu *vcpu)
4845 {
4846         struct kvm_run *kvm_run = vcpu->run;
4847
4848         kvm_run->psw_mask = vcpu->arch.sie_block->gpsw.mask;
4849         kvm_run->psw_addr = vcpu->arch.sie_block->gpsw.addr;
4850         kvm_run->s.regs.prefix = kvm_s390_get_prefix(vcpu);
4851         memcpy(&kvm_run->s.regs.crs, &vcpu->arch.sie_block->gcr, 128);
4852         kvm_run->s.regs.cputm = kvm_s390_get_cpu_timer(vcpu);
4853         kvm_run->s.regs.ckc = vcpu->arch.sie_block->ckc;
4854         kvm_run->s.regs.pft = vcpu->arch.pfault_token;
4855         kvm_run->s.regs.pfs = vcpu->arch.pfault_select;
4856         kvm_run->s.regs.pfc = vcpu->arch.pfault_compare;
4857         save_access_regs(vcpu->run->s.regs.acrs);
4858         restore_access_regs(vcpu->arch.host_acrs);
4859         /* Save guest register state */
4860         save_fpu_regs();
4861         vcpu->run->s.regs.fpc = current->thread.fpu.fpc;
4862         /* Restore will be done lazily at return */
4863         current->thread.fpu.fpc = vcpu->arch.host_fpregs.fpc;
4864         current->thread.fpu.regs = vcpu->arch.host_fpregs.regs;
4865         if (likely(!kvm_s390_pv_cpu_is_protected(vcpu)))
4866                 store_regs_fmt2(vcpu);
4867 }
4868
4869 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu)
4870 {
4871         struct kvm_run *kvm_run = vcpu->run;
4872         int rc;
4873
4874         /*
4875          * Running a VM while dumping always has the potential to
4876          * produce inconsistent dump data. But for PV vcpus a SIE
4877          * entry while dumping could also lead to a fatal validity
4878          * intercept which we absolutely want to avoid.
4879          */
4880         if (vcpu->kvm->arch.pv.dumping)
4881                 return -EINVAL;
4882
4883         if (kvm_run->immediate_exit)
4884                 return -EINTR;
4885
4886         if (kvm_run->kvm_valid_regs & ~KVM_SYNC_S390_VALID_FIELDS ||
4887             kvm_run->kvm_dirty_regs & ~KVM_SYNC_S390_VALID_FIELDS)
4888                 return -EINVAL;
4889
4890         vcpu_load(vcpu);
4891
4892         if (guestdbg_exit_pending(vcpu)) {
4893                 kvm_s390_prepare_debug_exit(vcpu);
4894                 rc = 0;
4895                 goto out;
4896         }
4897
4898         kvm_sigset_activate(vcpu);
4899
4900         /*
4901          * no need to check the return value of vcpu_start as it can only have
4902          * an error for protvirt, but protvirt means user cpu state
4903          */
4904         if (!kvm_s390_user_cpu_state_ctrl(vcpu->kvm)) {
4905                 kvm_s390_vcpu_start(vcpu);
4906         } else if (is_vcpu_stopped(vcpu)) {
4907                 pr_err_ratelimited("can't run stopped vcpu %d\n",
4908                                    vcpu->vcpu_id);
4909                 rc = -EINVAL;
4910                 goto out;
4911         }
4912
4913         sync_regs(vcpu);
4914         enable_cpu_timer_accounting(vcpu);
4915
4916         might_fault();
4917         rc = __vcpu_run(vcpu);
4918
4919         if (signal_pending(current) && !rc) {
4920                 kvm_run->exit_reason = KVM_EXIT_INTR;
4921                 rc = -EINTR;
4922         }
4923
4924         if (guestdbg_exit_pending(vcpu) && !rc)  {
4925                 kvm_s390_prepare_debug_exit(vcpu);
4926                 rc = 0;
4927         }
4928
4929         if (rc == -EREMOTE) {
4930                 /* userspace support is needed, kvm_run has been prepared */
4931                 rc = 0;
4932         }
4933
4934         disable_cpu_timer_accounting(vcpu);
4935         store_regs(vcpu);
4936
4937         kvm_sigset_deactivate(vcpu);
4938
4939         vcpu->stat.exit_userspace++;
4940 out:
4941         vcpu_put(vcpu);
4942         return rc;
4943 }
4944
4945 /*
4946  * store status at address
4947  * we use have two special cases:
4948  * KVM_S390_STORE_STATUS_NOADDR: -> 0x1200 on 64 bit
4949  * KVM_S390_STORE_STATUS_PREFIXED: -> prefix
4950  */
4951 int kvm_s390_store_status_unloaded(struct kvm_vcpu *vcpu, unsigned long gpa)
4952 {
4953         unsigned char archmode = 1;
4954         freg_t fprs[NUM_FPRS];
4955         unsigned int px;
4956         u64 clkcomp, cputm;
4957         int rc;
4958
4959         px = kvm_s390_get_prefix(vcpu);
4960         if (gpa == KVM_S390_STORE_STATUS_NOADDR) {
4961                 if (write_guest_abs(vcpu, 163, &archmode, 1))
4962                         return -EFAULT;
4963                 gpa = 0;
4964         } else if (gpa == KVM_S390_STORE_STATUS_PREFIXED) {
4965                 if (write_guest_real(vcpu, 163, &archmode, 1))
4966                         return -EFAULT;
4967                 gpa = px;
4968         } else
4969                 gpa -= __LC_FPREGS_SAVE_AREA;
4970
4971         /* manually convert vector registers if necessary */
4972         if (MACHINE_HAS_VX) {
4973                 convert_vx_to_fp(fprs, (__vector128 *) vcpu->run->s.regs.vrs);
4974                 rc = write_guest_abs(vcpu, gpa + __LC_FPREGS_SAVE_AREA,
4975                                      fprs, 128);
4976         } else {
4977                 rc = write_guest_abs(vcpu, gpa + __LC_FPREGS_SAVE_AREA,
4978                                      vcpu->run->s.regs.fprs, 128);
4979         }
4980         rc |= write_guest_abs(vcpu, gpa + __LC_GPREGS_SAVE_AREA,
4981                               vcpu->run->s.regs.gprs, 128);
4982         rc |= write_guest_abs(vcpu, gpa + __LC_PSW_SAVE_AREA,
4983                               &vcpu->arch.sie_block->gpsw, 16);
4984         rc |= write_guest_abs(vcpu, gpa + __LC_PREFIX_SAVE_AREA,
4985                               &px, 4);
4986         rc |= write_guest_abs(vcpu, gpa + __LC_FP_CREG_SAVE_AREA,
4987                               &vcpu->run->s.regs.fpc, 4);
4988         rc |= write_guest_abs(vcpu, gpa + __LC_TOD_PROGREG_SAVE_AREA,
4989                               &vcpu->arch.sie_block->todpr, 4);
4990         cputm = kvm_s390_get_cpu_timer(vcpu);
4991         rc |= write_guest_abs(vcpu, gpa + __LC_CPU_TIMER_SAVE_AREA,
4992                               &cputm, 8);
4993         clkcomp = vcpu->arch.sie_block->ckc >> 8;
4994         rc |= write_guest_abs(vcpu, gpa + __LC_CLOCK_COMP_SAVE_AREA,
4995                               &clkcomp, 8);
4996         rc |= write_guest_abs(vcpu, gpa + __LC_AREGS_SAVE_AREA,
4997                               &vcpu->run->s.regs.acrs, 64);
4998         rc |= write_guest_abs(vcpu, gpa + __LC_CREGS_SAVE_AREA,
4999                               &vcpu->arch.sie_block->gcr, 128);
5000         return rc ? -EFAULT : 0;
5001 }
5002
5003 int kvm_s390_vcpu_store_status(struct kvm_vcpu *vcpu, unsigned long addr)
5004 {
5005         /*
5006          * The guest FPRS and ACRS are in the host FPRS/ACRS due to the lazy
5007          * switch in the run ioctl. Let's update our copies before we save
5008          * it into the save area
5009          */
5010         save_fpu_regs();
5011         vcpu->run->s.regs.fpc = current->thread.fpu.fpc;
5012         save_access_regs(vcpu->run->s.regs.acrs);
5013
5014         return kvm_s390_store_status_unloaded(vcpu, addr);
5015 }
5016
5017 static void __disable_ibs_on_vcpu(struct kvm_vcpu *vcpu)
5018 {
5019         kvm_check_request(KVM_REQ_ENABLE_IBS, vcpu);
5020         kvm_s390_sync_request(KVM_REQ_DISABLE_IBS, vcpu);
5021 }
5022
5023 static void __disable_ibs_on_all_vcpus(struct kvm *kvm)
5024 {
5025         unsigned long i;
5026         struct kvm_vcpu *vcpu;
5027
5028         kvm_for_each_vcpu(i, vcpu, kvm) {
5029                 __disable_ibs_on_vcpu(vcpu);
5030         }
5031 }
5032
5033 static void __enable_ibs_on_vcpu(struct kvm_vcpu *vcpu)
5034 {
5035         if (!sclp.has_ibs)
5036                 return;
5037         kvm_check_request(KVM_REQ_DISABLE_IBS, vcpu);
5038         kvm_s390_sync_request(KVM_REQ_ENABLE_IBS, vcpu);
5039 }
5040
5041 int kvm_s390_vcpu_start(struct kvm_vcpu *vcpu)
5042 {
5043         int i, online_vcpus, r = 0, started_vcpus = 0;
5044
5045         if (!is_vcpu_stopped(vcpu))
5046                 return 0;
5047
5048         trace_kvm_s390_vcpu_start_stop(vcpu->vcpu_id, 1);
5049         /* Only one cpu at a time may enter/leave the STOPPED state. */
5050         spin_lock(&vcpu->kvm->arch.start_stop_lock);
5051         online_vcpus = atomic_read(&vcpu->kvm->online_vcpus);
5052
5053         /* Let's tell the UV that we want to change into the operating state */
5054         if (kvm_s390_pv_cpu_is_protected(vcpu)) {
5055                 r = kvm_s390_pv_set_cpu_state(vcpu, PV_CPU_STATE_OPR);
5056                 if (r) {
5057                         spin_unlock(&vcpu->kvm->arch.start_stop_lock);
5058                         return r;
5059                 }
5060         }
5061
5062         for (i = 0; i < online_vcpus; i++) {
5063                 if (!is_vcpu_stopped(kvm_get_vcpu(vcpu->kvm, i)))
5064                         started_vcpus++;
5065         }
5066
5067         if (started_vcpus == 0) {
5068                 /* we're the only active VCPU -> speed it up */
5069                 __enable_ibs_on_vcpu(vcpu);
5070         } else if (started_vcpus == 1) {
5071                 /*
5072                  * As we are starting a second VCPU, we have to disable
5073                  * the IBS facility on all VCPUs to remove potentially
5074                  * outstanding ENABLE requests.
5075                  */
5076                 __disable_ibs_on_all_vcpus(vcpu->kvm);
5077         }
5078
5079         kvm_s390_clear_cpuflags(vcpu, CPUSTAT_STOPPED);
5080         /*
5081          * The real PSW might have changed due to a RESTART interpreted by the
5082          * ultravisor. We block all interrupts and let the next sie exit
5083          * refresh our view.
5084          */
5085         if (kvm_s390_pv_cpu_is_protected(vcpu))
5086                 vcpu->arch.sie_block->gpsw.mask &= ~PSW_INT_MASK;
5087         /*
5088          * Another VCPU might have used IBS while we were offline.
5089          * Let's play safe and flush the VCPU at startup.
5090          */
5091         kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
5092         spin_unlock(&vcpu->kvm->arch.start_stop_lock);
5093         return 0;
5094 }
5095
5096 int kvm_s390_vcpu_stop(struct kvm_vcpu *vcpu)
5097 {
5098         int i, online_vcpus, r = 0, started_vcpus = 0;
5099         struct kvm_vcpu *started_vcpu = NULL;
5100
5101         if (is_vcpu_stopped(vcpu))
5102                 return 0;
5103
5104         trace_kvm_s390_vcpu_start_stop(vcpu->vcpu_id, 0);
5105         /* Only one cpu at a time may enter/leave the STOPPED state. */
5106         spin_lock(&vcpu->kvm->arch.start_stop_lock);
5107         online_vcpus = atomic_read(&vcpu->kvm->online_vcpus);
5108
5109         /* Let's tell the UV that we want to change into the stopped state */
5110         if (kvm_s390_pv_cpu_is_protected(vcpu)) {
5111                 r = kvm_s390_pv_set_cpu_state(vcpu, PV_CPU_STATE_STP);
5112                 if (r) {
5113                         spin_unlock(&vcpu->kvm->arch.start_stop_lock);
5114                         return r;
5115                 }
5116         }
5117
5118         /*
5119          * Set the VCPU to STOPPED and THEN clear the interrupt flag,
5120          * now that the SIGP STOP and SIGP STOP AND STORE STATUS orders
5121          * have been fully processed. This will ensure that the VCPU
5122          * is kept BUSY if another VCPU is inquiring with SIGP SENSE.
5123          */
5124         kvm_s390_set_cpuflags(vcpu, CPUSTAT_STOPPED);
5125         kvm_s390_clear_stop_irq(vcpu);
5126
5127         __disable_ibs_on_vcpu(vcpu);
5128
5129         for (i = 0; i < online_vcpus; i++) {
5130                 struct kvm_vcpu *tmp = kvm_get_vcpu(vcpu->kvm, i);
5131
5132                 if (!is_vcpu_stopped(tmp)) {
5133                         started_vcpus++;
5134                         started_vcpu = tmp;
5135                 }
5136         }
5137
5138         if (started_vcpus == 1) {
5139                 /*
5140                  * As we only have one VCPU left, we want to enable the
5141                  * IBS facility for that VCPU to speed it up.
5142                  */
5143                 __enable_ibs_on_vcpu(started_vcpu);
5144         }
5145
5146         spin_unlock(&vcpu->kvm->arch.start_stop_lock);
5147         return 0;
5148 }
5149
5150 static int kvm_vcpu_ioctl_enable_cap(struct kvm_vcpu *vcpu,
5151                                      struct kvm_enable_cap *cap)
5152 {
5153         int r;
5154
5155         if (cap->flags)
5156                 return -EINVAL;
5157
5158         switch (cap->cap) {
5159         case KVM_CAP_S390_CSS_SUPPORT:
5160                 if (!vcpu->kvm->arch.css_support) {
5161                         vcpu->kvm->arch.css_support = 1;
5162                         VM_EVENT(vcpu->kvm, 3, "%s", "ENABLE: CSS support");
5163                         trace_kvm_s390_enable_css(vcpu->kvm);
5164                 }
5165                 r = 0;
5166                 break;
5167         default:
5168                 r = -EINVAL;
5169                 break;
5170         }
5171         return r;
5172 }
5173
5174 static long kvm_s390_vcpu_sida_op(struct kvm_vcpu *vcpu,
5175                                   struct kvm_s390_mem_op *mop)
5176 {
5177         void __user *uaddr = (void __user *)mop->buf;
5178         int r = 0;
5179
5180         if (mop->flags || !mop->size)
5181                 return -EINVAL;
5182         if (mop->size + mop->sida_offset < mop->size)
5183                 return -EINVAL;
5184         if (mop->size + mop->sida_offset > sida_size(vcpu->arch.sie_block))
5185                 return -E2BIG;
5186         if (!kvm_s390_pv_cpu_is_protected(vcpu))
5187                 return -EINVAL;
5188
5189         switch (mop->op) {
5190         case KVM_S390_MEMOP_SIDA_READ:
5191                 if (copy_to_user(uaddr, (void *)(sida_origin(vcpu->arch.sie_block) +
5192                                  mop->sida_offset), mop->size))
5193                         r = -EFAULT;
5194
5195                 break;
5196         case KVM_S390_MEMOP_SIDA_WRITE:
5197                 if (copy_from_user((void *)(sida_origin(vcpu->arch.sie_block) +
5198                                    mop->sida_offset), uaddr, mop->size))
5199                         r = -EFAULT;
5200                 break;
5201         }
5202         return r;
5203 }
5204
5205 static long kvm_s390_vcpu_mem_op(struct kvm_vcpu *vcpu,
5206                                  struct kvm_s390_mem_op *mop)
5207 {
5208         void __user *uaddr = (void __user *)mop->buf;
5209         void *tmpbuf = NULL;
5210         int r = 0;
5211         const u64 supported_flags = KVM_S390_MEMOP_F_INJECT_EXCEPTION
5212                                     | KVM_S390_MEMOP_F_CHECK_ONLY
5213                                     | KVM_S390_MEMOP_F_SKEY_PROTECTION;
5214
5215         if (mop->flags & ~supported_flags || mop->ar >= NUM_ACRS || !mop->size)
5216                 return -EINVAL;
5217         if (mop->size > MEM_OP_MAX_SIZE)
5218                 return -E2BIG;
5219         if (kvm_s390_pv_cpu_is_protected(vcpu))
5220                 return -EINVAL;
5221         if (mop->flags & KVM_S390_MEMOP_F_SKEY_PROTECTION) {
5222                 if (access_key_invalid(mop->key))
5223                         return -EINVAL;
5224         } else {
5225                 mop->key = 0;
5226         }
5227         if (!(mop->flags & KVM_S390_MEMOP_F_CHECK_ONLY)) {
5228                 tmpbuf = vmalloc(mop->size);
5229                 if (!tmpbuf)
5230                         return -ENOMEM;
5231         }
5232
5233         switch (mop->op) {
5234         case KVM_S390_MEMOP_LOGICAL_READ:
5235                 if (mop->flags & KVM_S390_MEMOP_F_CHECK_ONLY) {
5236                         r = check_gva_range(vcpu, mop->gaddr, mop->ar, mop->size,
5237                                             GACC_FETCH, mop->key);
5238                         break;
5239                 }
5240                 r = read_guest_with_key(vcpu, mop->gaddr, mop->ar, tmpbuf,
5241                                         mop->size, mop->key);
5242                 if (r == 0) {
5243                         if (copy_to_user(uaddr, tmpbuf, mop->size))
5244                                 r = -EFAULT;
5245                 }
5246                 break;
5247         case KVM_S390_MEMOP_LOGICAL_WRITE:
5248                 if (mop->flags & KVM_S390_MEMOP_F_CHECK_ONLY) {
5249                         r = check_gva_range(vcpu, mop->gaddr, mop->ar, mop->size,
5250                                             GACC_STORE, mop->key);
5251                         break;
5252                 }
5253                 if (copy_from_user(tmpbuf, uaddr, mop->size)) {
5254                         r = -EFAULT;
5255                         break;
5256                 }
5257                 r = write_guest_with_key(vcpu, mop->gaddr, mop->ar, tmpbuf,
5258                                          mop->size, mop->key);
5259                 break;
5260         }
5261
5262         if (r > 0 && (mop->flags & KVM_S390_MEMOP_F_INJECT_EXCEPTION) != 0)
5263                 kvm_s390_inject_prog_irq(vcpu, &vcpu->arch.pgm);
5264
5265         vfree(tmpbuf);
5266         return r;
5267 }
5268
5269 static long kvm_s390_vcpu_memsida_op(struct kvm_vcpu *vcpu,
5270                                      struct kvm_s390_mem_op *mop)
5271 {
5272         int r, srcu_idx;
5273
5274         srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
5275
5276         switch (mop->op) {
5277         case KVM_S390_MEMOP_LOGICAL_READ:
5278         case KVM_S390_MEMOP_LOGICAL_WRITE:
5279                 r = kvm_s390_vcpu_mem_op(vcpu, mop);
5280                 break;
5281         case KVM_S390_MEMOP_SIDA_READ:
5282         case KVM_S390_MEMOP_SIDA_WRITE:
5283                 /* we are locked against sida going away by the vcpu->mutex */
5284                 r = kvm_s390_vcpu_sida_op(vcpu, mop);
5285                 break;
5286         default:
5287                 r = -EINVAL;
5288         }
5289
5290         srcu_read_unlock(&vcpu->kvm->srcu, srcu_idx);
5291         return r;
5292 }
5293
5294 long kvm_arch_vcpu_async_ioctl(struct file *filp,
5295                                unsigned int ioctl, unsigned long arg)
5296 {
5297         struct kvm_vcpu *vcpu = filp->private_data;
5298         void __user *argp = (void __user *)arg;
5299
5300         switch (ioctl) {
5301         case KVM_S390_IRQ: {
5302                 struct kvm_s390_irq s390irq;
5303
5304                 if (copy_from_user(&s390irq, argp, sizeof(s390irq)))
5305                         return -EFAULT;
5306                 return kvm_s390_inject_vcpu(vcpu, &s390irq);
5307         }
5308         case KVM_S390_INTERRUPT: {
5309                 struct kvm_s390_interrupt s390int;
5310                 struct kvm_s390_irq s390irq = {};
5311
5312                 if (copy_from_user(&s390int, argp, sizeof(s390int)))
5313                         return -EFAULT;
5314                 if (s390int_to_s390irq(&s390int, &s390irq))
5315                         return -EINVAL;
5316                 return kvm_s390_inject_vcpu(vcpu, &s390irq);
5317         }
5318         }
5319         return -ENOIOCTLCMD;
5320 }
5321
5322 static int kvm_s390_handle_pv_vcpu_dump(struct kvm_vcpu *vcpu,
5323                                         struct kvm_pv_cmd *cmd)
5324 {
5325         struct kvm_s390_pv_dmp dmp;
5326         void *data;
5327         int ret;
5328
5329         /* Dump initialization is a prerequisite */
5330         if (!vcpu->kvm->arch.pv.dumping)
5331                 return -EINVAL;
5332
5333         if (copy_from_user(&dmp, (__u8 __user *)cmd->data, sizeof(dmp)))
5334                 return -EFAULT;
5335
5336         /* We only handle this subcmd right now */
5337         if (dmp.subcmd != KVM_PV_DUMP_CPU)
5338                 return -EINVAL;
5339
5340         /* CPU dump length is the same as create cpu storage donation. */
5341         if (dmp.buff_len != uv_info.guest_cpu_stor_len)
5342                 return -EINVAL;
5343
5344         data = kvzalloc(uv_info.guest_cpu_stor_len, GFP_KERNEL);
5345         if (!data)
5346                 return -ENOMEM;
5347
5348         ret = kvm_s390_pv_dump_cpu(vcpu, data, &cmd->rc, &cmd->rrc);
5349
5350         VCPU_EVENT(vcpu, 3, "PROTVIRT DUMP CPU %d rc %x rrc %x",
5351                    vcpu->vcpu_id, cmd->rc, cmd->rrc);
5352
5353         if (ret)
5354                 ret = -EINVAL;
5355
5356         /* On success copy over the dump data */
5357         if (!ret && copy_to_user((__u8 __user *)dmp.buff_addr, data, uv_info.guest_cpu_stor_len))
5358                 ret = -EFAULT;
5359
5360         kvfree(data);
5361         return ret;
5362 }
5363
5364 long kvm_arch_vcpu_ioctl(struct file *filp,
5365                          unsigned int ioctl, unsigned long arg)
5366 {
5367         struct kvm_vcpu *vcpu = filp->private_data;
5368         void __user *argp = (void __user *)arg;
5369         int idx;
5370         long r;
5371         u16 rc, rrc;
5372
5373         vcpu_load(vcpu);
5374
5375         switch (ioctl) {
5376         case KVM_S390_STORE_STATUS:
5377                 idx = srcu_read_lock(&vcpu->kvm->srcu);
5378                 r = kvm_s390_store_status_unloaded(vcpu, arg);
5379                 srcu_read_unlock(&vcpu->kvm->srcu, idx);
5380                 break;
5381         case KVM_S390_SET_INITIAL_PSW: {
5382                 psw_t psw;
5383
5384                 r = -EFAULT;
5385                 if (copy_from_user(&psw, argp, sizeof(psw)))
5386                         break;
5387                 r = kvm_arch_vcpu_ioctl_set_initial_psw(vcpu, psw);
5388                 break;
5389         }
5390         case KVM_S390_CLEAR_RESET:
5391                 r = 0;
5392                 kvm_arch_vcpu_ioctl_clear_reset(vcpu);
5393                 if (kvm_s390_pv_cpu_is_protected(vcpu)) {
5394                         r = uv_cmd_nodata(kvm_s390_pv_cpu_get_handle(vcpu),
5395                                           UVC_CMD_CPU_RESET_CLEAR, &rc, &rrc);
5396                         VCPU_EVENT(vcpu, 3, "PROTVIRT RESET CLEAR VCPU: rc %x rrc %x",
5397                                    rc, rrc);
5398                 }
5399                 break;
5400         case KVM_S390_INITIAL_RESET:
5401                 r = 0;
5402                 kvm_arch_vcpu_ioctl_initial_reset(vcpu);
5403                 if (kvm_s390_pv_cpu_is_protected(vcpu)) {
5404                         r = uv_cmd_nodata(kvm_s390_pv_cpu_get_handle(vcpu),
5405                                           UVC_CMD_CPU_RESET_INITIAL,
5406                                           &rc, &rrc);
5407                         VCPU_EVENT(vcpu, 3, "PROTVIRT RESET INITIAL VCPU: rc %x rrc %x",
5408                                    rc, rrc);
5409                 }
5410                 break;
5411         case KVM_S390_NORMAL_RESET:
5412                 r = 0;
5413                 kvm_arch_vcpu_ioctl_normal_reset(vcpu);
5414                 if (kvm_s390_pv_cpu_is_protected(vcpu)) {
5415                         r = uv_cmd_nodata(kvm_s390_pv_cpu_get_handle(vcpu),
5416                                           UVC_CMD_CPU_RESET, &rc, &rrc);
5417                         VCPU_EVENT(vcpu, 3, "PROTVIRT RESET NORMAL VCPU: rc %x rrc %x",
5418                                    rc, rrc);
5419                 }
5420                 break;
5421         case KVM_SET_ONE_REG:
5422         case KVM_GET_ONE_REG: {
5423                 struct kvm_one_reg reg;
5424                 r = -EINVAL;
5425                 if (kvm_s390_pv_cpu_is_protected(vcpu))
5426                         break;
5427                 r = -EFAULT;
5428                 if (copy_from_user(&reg, argp, sizeof(reg)))
5429                         break;
5430                 if (ioctl == KVM_SET_ONE_REG)
5431                         r = kvm_arch_vcpu_ioctl_set_one_reg(vcpu, &reg);
5432                 else
5433                         r = kvm_arch_vcpu_ioctl_get_one_reg(vcpu, &reg);
5434                 break;
5435         }
5436 #ifdef CONFIG_KVM_S390_UCONTROL
5437         case KVM_S390_UCAS_MAP: {
5438                 struct kvm_s390_ucas_mapping ucasmap;
5439
5440                 if (copy_from_user(&ucasmap, argp, sizeof(ucasmap))) {
5441                         r = -EFAULT;
5442                         break;
5443                 }
5444
5445                 if (!kvm_is_ucontrol(vcpu->kvm)) {
5446                         r = -EINVAL;
5447                         break;
5448                 }
5449
5450                 r = gmap_map_segment(vcpu->arch.gmap, ucasmap.user_addr,
5451                                      ucasmap.vcpu_addr, ucasmap.length);
5452                 break;
5453         }
5454         case KVM_S390_UCAS_UNMAP: {
5455                 struct kvm_s390_ucas_mapping ucasmap;
5456
5457                 if (copy_from_user(&ucasmap, argp, sizeof(ucasmap))) {
5458                         r = -EFAULT;
5459                         break;
5460                 }
5461
5462                 if (!kvm_is_ucontrol(vcpu->kvm)) {
5463                         r = -EINVAL;
5464                         break;
5465                 }
5466
5467                 r = gmap_unmap_segment(vcpu->arch.gmap, ucasmap.vcpu_addr,
5468                         ucasmap.length);
5469                 break;
5470         }
5471 #endif
5472         case KVM_S390_VCPU_FAULT: {
5473                 r = gmap_fault(vcpu->arch.gmap, arg, 0);
5474                 break;
5475         }
5476         case KVM_ENABLE_CAP:
5477         {
5478                 struct kvm_enable_cap cap;
5479                 r = -EFAULT;
5480                 if (copy_from_user(&cap, argp, sizeof(cap)))
5481                         break;
5482                 r = kvm_vcpu_ioctl_enable_cap(vcpu, &cap);
5483                 break;
5484         }
5485         case KVM_S390_MEM_OP: {
5486                 struct kvm_s390_mem_op mem_op;
5487
5488                 if (copy_from_user(&mem_op, argp, sizeof(mem_op)) == 0)
5489                         r = kvm_s390_vcpu_memsida_op(vcpu, &mem_op);
5490                 else
5491                         r = -EFAULT;
5492                 break;
5493         }
5494         case KVM_S390_SET_IRQ_STATE: {
5495                 struct kvm_s390_irq_state irq_state;
5496
5497                 r = -EFAULT;
5498                 if (copy_from_user(&irq_state, argp, sizeof(irq_state)))
5499                         break;
5500                 if (irq_state.len > VCPU_IRQS_MAX_BUF ||
5501                     irq_state.len == 0 ||
5502                     irq_state.len % sizeof(struct kvm_s390_irq) > 0) {
5503                         r = -EINVAL;
5504                         break;
5505                 }
5506                 /* do not use irq_state.flags, it will break old QEMUs */
5507                 r = kvm_s390_set_irq_state(vcpu,
5508                                            (void __user *) irq_state.buf,
5509                                            irq_state.len);
5510                 break;
5511         }
5512         case KVM_S390_GET_IRQ_STATE: {
5513                 struct kvm_s390_irq_state irq_state;
5514
5515                 r = -EFAULT;
5516                 if (copy_from_user(&irq_state, argp, sizeof(irq_state)))
5517                         break;
5518                 if (irq_state.len == 0) {
5519                         r = -EINVAL;
5520                         break;
5521                 }
5522                 /* do not use irq_state.flags, it will break old QEMUs */
5523                 r = kvm_s390_get_irq_state(vcpu,
5524                                            (__u8 __user *)  irq_state.buf,
5525                                            irq_state.len);
5526                 break;
5527         }
5528         case KVM_S390_PV_CPU_COMMAND: {
5529                 struct kvm_pv_cmd cmd;
5530
5531                 r = -EINVAL;
5532                 if (!is_prot_virt_host())
5533                         break;
5534
5535                 r = -EFAULT;
5536                 if (copy_from_user(&cmd, argp, sizeof(cmd)))
5537                         break;
5538
5539                 r = -EINVAL;
5540                 if (cmd.flags)
5541                         break;
5542
5543                 /* We only handle this cmd right now */
5544                 if (cmd.cmd != KVM_PV_DUMP)
5545                         break;
5546
5547                 r = kvm_s390_handle_pv_vcpu_dump(vcpu, &cmd);
5548
5549                 /* Always copy over UV rc / rrc data */
5550                 if (copy_to_user((__u8 __user *)argp, &cmd.rc,
5551                                  sizeof(cmd.rc) + sizeof(cmd.rrc)))
5552                         r = -EFAULT;
5553                 break;
5554         }
5555         default:
5556                 r = -ENOTTY;
5557         }
5558
5559         vcpu_put(vcpu);
5560         return r;
5561 }
5562
5563 vm_fault_t kvm_arch_vcpu_fault(struct kvm_vcpu *vcpu, struct vm_fault *vmf)
5564 {
5565 #ifdef CONFIG_KVM_S390_UCONTROL
5566         if ((vmf->pgoff == KVM_S390_SIE_PAGE_OFFSET)
5567                  && (kvm_is_ucontrol(vcpu->kvm))) {
5568                 vmf->page = virt_to_page(vcpu->arch.sie_block);
5569                 get_page(vmf->page);
5570                 return 0;
5571         }
5572 #endif
5573         return VM_FAULT_SIGBUS;
5574 }
5575
5576 /* Section: memory related */
5577 int kvm_arch_prepare_memory_region(struct kvm *kvm,
5578                                    const struct kvm_memory_slot *old,
5579                                    struct kvm_memory_slot *new,
5580                                    enum kvm_mr_change change)
5581 {
5582         gpa_t size;
5583
5584         /* When we are protected, we should not change the memory slots */
5585         if (kvm_s390_pv_get_handle(kvm))
5586                 return -EINVAL;
5587
5588         if (change != KVM_MR_DELETE && change != KVM_MR_FLAGS_ONLY) {
5589                 /*
5590                  * A few sanity checks. We can have memory slots which have to be
5591                  * located/ended at a segment boundary (1MB). The memory in userland is
5592                  * ok to be fragmented into various different vmas. It is okay to mmap()
5593                  * and munmap() stuff in this slot after doing this call at any time
5594                  */
5595
5596                 if (new->userspace_addr & 0xffffful)
5597                         return -EINVAL;
5598
5599                 size = new->npages * PAGE_SIZE;
5600                 if (size & 0xffffful)
5601                         return -EINVAL;
5602
5603                 if ((new->base_gfn * PAGE_SIZE) + size > kvm->arch.mem_limit)
5604                         return -EINVAL;
5605         }
5606
5607         if (!kvm->arch.migration_mode)
5608                 return 0;
5609
5610         /*
5611          * Turn off migration mode when:
5612          * - userspace creates a new memslot with dirty logging off,
5613          * - userspace modifies an existing memslot (MOVE or FLAGS_ONLY) and
5614          *   dirty logging is turned off.
5615          * Migration mode expects dirty page logging being enabled to store
5616          * its dirty bitmap.
5617          */
5618         if (change != KVM_MR_DELETE &&
5619             !(new->flags & KVM_MEM_LOG_DIRTY_PAGES))
5620                 WARN(kvm_s390_vm_stop_migration(kvm),
5621                      "Failed to stop migration mode");
5622
5623         return 0;
5624 }
5625
5626 void kvm_arch_commit_memory_region(struct kvm *kvm,
5627                                 struct kvm_memory_slot *old,
5628                                 const struct kvm_memory_slot *new,
5629                                 enum kvm_mr_change change)
5630 {
5631         int rc = 0;
5632
5633         switch (change) {
5634         case KVM_MR_DELETE:
5635                 rc = gmap_unmap_segment(kvm->arch.gmap, old->base_gfn * PAGE_SIZE,
5636                                         old->npages * PAGE_SIZE);
5637                 break;
5638         case KVM_MR_MOVE:
5639                 rc = gmap_unmap_segment(kvm->arch.gmap, old->base_gfn * PAGE_SIZE,
5640                                         old->npages * PAGE_SIZE);
5641                 if (rc)
5642                         break;
5643                 fallthrough;
5644         case KVM_MR_CREATE:
5645                 rc = gmap_map_segment(kvm->arch.gmap, new->userspace_addr,
5646                                       new->base_gfn * PAGE_SIZE,
5647                                       new->npages * PAGE_SIZE);
5648                 break;
5649         case KVM_MR_FLAGS_ONLY:
5650                 break;
5651         default:
5652                 WARN(1, "Unknown KVM MR CHANGE: %d\n", change);
5653         }
5654         if (rc)
5655                 pr_warn("failed to commit memory region\n");
5656         return;
5657 }
5658
5659 static inline unsigned long nonhyp_mask(int i)
5660 {
5661         unsigned int nonhyp_fai = (sclp.hmfai << i * 2) >> 30;
5662
5663         return 0x0000ffffffffffffUL >> (nonhyp_fai << 4);
5664 }
5665
5666 static int __init kvm_s390_init(void)
5667 {
5668         int i;
5669
5670         if (!sclp.has_sief2) {
5671                 pr_info("SIE is not available\n");
5672                 return -ENODEV;
5673         }
5674
5675         if (nested && hpage) {
5676                 pr_info("A KVM host that supports nesting cannot back its KVM guests with huge pages\n");
5677                 return -EINVAL;
5678         }
5679
5680         for (i = 0; i < 16; i++)
5681                 kvm_s390_fac_base[i] |=
5682                         stfle_fac_list[i] & nonhyp_mask(i);
5683
5684         return kvm_init(NULL, sizeof(struct kvm_vcpu), 0, THIS_MODULE);
5685 }
5686
5687 static void __exit kvm_s390_exit(void)
5688 {
5689         kvm_exit();
5690 }
5691
5692 module_init(kvm_s390_init);
5693 module_exit(kvm_s390_exit);
5694
5695 /*
5696  * Enable autoloading of the kvm module.
5697  * Note that we add the module alias here instead of virt/kvm/kvm_main.c
5698  * since x86 takes a different approach.
5699  */
5700 #include <linux/miscdevice.h>
5701 MODULE_ALIAS_MISCDEV(KVM_MINOR);
5702 MODULE_ALIAS("devname:kvm");