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