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